Ruby Big Decimal Fixed Number Rounding

I want to round BigDecimal in a ruby. I know I can use the round function, but

round function gives

 (3.2).round(2) => 3.2 

I want

 (3.2).round(2) => 3.20 (3.20).round(2) => 3.20 (3).round(2) => 3.00 (3.578).round(2) => 3.58 

I always want to have 2 decimal places, 3.20 not 3.2

any idea how to do this?

+6
source share
2 answers

try the following:

 '%.2f' % 3.2 => "3.20" '%.2f' % 3 => "3.00" '%.2f' % 3.578 => "3.58" etc. 
+15
source

Unlike, for example, Java BigDecimal , Ruby BigDecimal does not have accuracy for each instance. The difference between 3.2 and 3.20 in Ruby BigDecimal is just formatting.

+5
source

All Articles