Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you write a float value up to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you round something to 2 decimal places?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

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

Ruby has a built in function round() which allows us to both change floats to integers, and round floats to decimal places. round() with no argument will round to 0 decimals, which will return an integer type number. Using round(1) will round to one decimal, and round(2) will round to two decimals.

How do you round off a float?

Round() Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.


(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.


Edit

After getting feedback, It seems the original solution didn't work. That's why updated the answer as one of the suggestions.

def float_of_2_decimal(float_n) 
  float_n.to_d.round(2, :truncate).to_f
end

Other answers may work, if you want to have rounded numbers of 2 decimal places. But, If you want to have floating point numbers with first two decimal places without rounding, Those answers won't help.

So, to get a floating point number with first two decimal places, I used this technique. Doesn't work in some cases

def float_of_2_decimal(float_n)
  float_n.round(3).to_s[0..3].to_f
end

with 5.666666666666666666666666, it will return 5.66 instead of rounded 5.67. Hope it will help someone