Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

290
Visualizações
Move decimal fixed number of spaces with Ruby

I have large integers (typically 15-30 digits) stored as a string that represent a certain amount of a given currenty (such as ETH). Also stored with that is the number of digits to move the decimal.

{
    "base_price"=>"5000000000000000000",
    "decimals"=>18
}

The output that I'm ultimately looking for is 5.00 (which is what you'd get if took the decimal from 5000000000000000000 and moved it to the left 18 positions).

How would I do that in Ruby?

over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Given:

my_map = {
    "base_price"=>"5000000000000000000",
    "decimals"=>18
}

You could use:

my_number = my_map["base_price"].to_i / (10**my_map["decimals"]).to_f
puts(my_number)
over 4 years ago · Santiago Trujillo Relatório

0

h = { "base_price"=>"5000000000000000000", "decimals"=>18 }
​
bef, aft = h["base_price"].split(/(?=\d{#{h["decimals"]}}\z)/)
  #=> ["5", "000000000000000000"]

bef + '.' + aft[0,2]
  #=> "5.00"

The regular expression uses the positive lookahead (?=\d{18}\z) to split the string at a ("zero-width") location between digits such that 18 digits follow to the end of the string.

Alternatively, one could write:

str = h["base_price"][0, h["base_price"].size-h["decimals"]+2]
  #=> h["base_price"][0, 3]
  #=> "500"
str.insert(str.size-2, '.')
  #=> "5.00"

Neither of these address potential boundary cases such as

{ "base_price"=>"500", "decimals"=>1 }

or

{ "base_price"=>"500", "decimals"=>4 }

Nor do they consider rounding issues.

over 4 years ago · Santiago Trujillo Relatório

0

Regular expressions and interpolation?

my_map = {
    "base_price"=>"5000000000000000000",
    "decimals"=>18
}

my_map["base_price"].sub(
    /(0{#{my_map["decimals"]}})\s*$/, 
    ".#{$1}"
)

The number of decimal places is interpolated into the regular expression as the count of zeroes to look for from the end of the string (plus zero or more whitespace characters). This is matched, and the match is subbed with a . in front of it.

Producing:

=> "5.000000000000000000"
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda