Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

288
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!