How do you round a float to 2 decimal places in JRuby? How do you round a float to 2 decimal places in JRuby? ruby ruby

How do you round a float to 2 decimal places in JRuby?


(5.65235534).round(2)#=> 5.65


sprintf('%.2f', number) is a cryptic, but very powerful way of formatting numbers. The result is always a string, but since you're rounding I assume you're doing it for presentation purposes anyway. sprintf can format any number almost any way you like, and lots more.

Full sprintf documentation: http://www.ruby-doc.org/core-2.0.0/Kernel.html#method-i-sprintf


Float#round can take a parameter in Ruby 1.9, not in Ruby 1.8. JRuby defaults to 1.8, but it is capable of running in 1.9 mode.