Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Float Conversion to Cents

Tags:

ruby

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?

Example input and output:

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

IMO: this is not a duplicate of this question because I am aware that float is not broken.

like image 519
Neil Avatar asked Nov 07 '16 16:11

Neil


1 Answers

Use round:

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

As discussed in comments, there is a potentially better way to deal with such strings - BigDecimal class:

(BigDecimal.new('67.99') * 100).round
#=> 6799

This becomes relevant for large numbers:

input = '1000000000000001'

(input.to_f * 100).round
#=> 100000000000000096

(BigDecimal.new(input) * 100).round
#=> 100000000000000100
like image 143
Andrey Deineko Avatar answered Oct 19 '22 19:10

Andrey Deineko