Convert cents to dollar string in Ruby without using BigDecimal

I want to convert from cents to dollars correctly in Ruby. I will never have to work with a fraction of a cent.

Is it possible to do this correctly (without floating point errors) without using BigDecimal?

For example, cents in dollars

"99" => "0.99"
"324" => "3.24"

The following seems to work, but is this true?

(cents.to_i/100.0).to_s
+5
source share
4 answers

As Mikel Kohl already answered : Look at the money stone.

Example:

require 'money'
Money.use_i18n = false  #https://stackoverflow.com/q/31133229/676874
puts Money.new( 99, 'USD')
puts Money.new(324, 'USD')

The following seems to work, but is this true?

(cents.to_i/100.0).to_s

At first glance, this is normal, but:

cents = '10'
p (cents.to_i/100.0).to_s # -> '0.1'

You do not have two digits.

Alternative:

p '%.2f' % (cents.to_i/100.0) # -> '0.10'
+8
source

, :

# There are, of course, all sorts of ways to do this.
def add_decimal(s)
    pfx = [ '0.00', '0.0', '0.' ]
    if(pfx[s.length])
        s = pfx[s.length] + s
    else
        s = s.dup
        s[-2, 0] = '.'
    end
    s
end

add_decimal('')      #   "0.00" 
add_decimal('1')     #   "0.01" 
add_decimal('12')    #   "0.12" 
add_decimal('123')   #   "1.23" 
add_decimal('1234')  #  "12.34" 
add_decimal('12345') # "123.45"

, , , Rational, , . , , , .

+4

. ( ):

Money, , ​​ .

Money:: Currency, .

, . .

Represents a currency as Money :: Currency instances providing a high level of flexibility.

Provides an API for exchanging money from one currency to another.

Has the ability to analyze money and currency lines in the corresponding object Money / Currency.

+3
source

You can also use Rationals. However, I'm not sure if they convert to float when sprintf-ed:

"%.2f" % Rational("324".to_i,100)
#=> "3.24"
"%.2f" % Rational("99".to_i,100)
#=> "0.99"
"%.2f" % Rational("80".to_i,100)
#=> "0.80"
"%.2f" % Rational("12380".to_i,100)
#=> "123.80"
+1
source

All Articles