Gediminas Šukys
Gediminas Šukys

Reputation: 7391

Converting currency needs proper round(2)

This is my code to convert local currency to EUR

price_eur = price.to_i / 3.4528
price_eur = price_eur.round(2)

The problem is, if price=0.8, I get result price_eur=0.0, why?

How to make it 0.80 (proper value AND always leading zero)?

Upvotes: 0

Views: 41

Answers (2)

joshua.paling
joshua.paling

Reputation: 13952

to_i rounds down to the nearest integer - so 0.8.to_i is zero. And then zero over anything else remains zero.

You can't use an integer - use a float. price.to_f

And then, use sprintf('%.2f', price_eur) to print it as a string, with a leading zero.

pry 2.1.2 (main):0 > price = 0.8
0.8
=>
pry 2.1.2 (main):0 > price_eur = price.to_f / 3.4528
0.23169601482854496
=>
pry 2.1.2 (main):0 > price_eur = price_eur.round(2)
0.23
=>
pry 2.1.2 (main):0 > sprintf('%.2f', price_eur)
"0.23"
=>
pry 2.1.2 (main):0 >

Edit: note comment from @Stefan not to use floats, and to use BigDecimal instead. Really, the easiest way to deal with money is probably to use the Money gem, which already handles a lot of these problems: https://github.com/RubyMoney/money

Upvotes: 1

sawa
sawa

Reputation: 168249

  1. Because 0.8.to_i is 0.

  2. It is impossible.

Upvotes: 1

Related Questions