-1

Actually I do not know how this is called and that is why I ask here.

I am working with currency and this way of presentation is important.

In ruby I need to have a value like 2.20 and not 2.2.

Examples:

2.201.round(2) -> 2.20 and not 2.2

3.80989.round(2) -> 3.80 and not 3.8

The problem is with the final 0, when it is another number there is no problem. 2.345.round(2) -> 2.35

Any idea?

karlihnos
  • 415
  • 1
  • 7
  • 22

2 Answers2

4

Something like this using formatting

x = 2.2
puts "%.2f" %x # => 2.20

When dealing with money and currencies, you shouldn't trust floating point numbers. Why? Check this.

There is a special gem for dealing with money.

Community
  • 1
  • 1
mic-kul
  • 989
  • 3
  • 16
  • 26
3

You can use sprintf method:

sprintf('%.2f', 2.201)
# => '2.20'
Marek Lipka
  • 50,622
  • 7
  • 87
  • 91