Neil Neil - 25 days ago 18
Ruby Question

Ruby Float Conversion to Cents

A user enters the string

'67.99'
. I need to ultimately convert this into the integer
6799
.


  • In other words: convert the currency amount entered via a
    string
    into cents via
    integer
    data type.



I notice that this happens:

('67.99'.to_f * 100).to_i
=> 6798


Not expected behavior. I need to save it as
6799
, not
6798
.

The issue is multiplying this float number by 100:

`67.99'.to_f * 100
=> 6798.999999999999


Question: How can I properly convert a decimal, entered as a string, into an integer?

tests:

67 => 6700
67. => 6700
67.9 => 6790
67.99 => 6799

Answer

Use round:

('67.99'.to_f * 100).round
#=> 6799
Comments