Home > Software engineering >  Move decimal fixed number of spaces with Ruby
Move decimal fixed number of spaces with Ruby

Time:10-26

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?

CodePudding user response:

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)

CodePudding user response:

h = { "base_price"=>"5000000000000000000", "decimals"=>18 }
bef, aft = h["base_price"].split(/(?=\d{18}\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.

This does not address potential boundary cases such as

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

or

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

Nor does it consider rounding issues.

CodePudding user response:

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"
  • Related