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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With