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

RubyJrubyRounding

Ruby Problem Overview


How do you round a float to 2 decimal places in JRuby(1.6.x)?

number = 1.1164
number.round(2)

# The above shows the following error
# wrong number of arguments (1 for 0)

Ruby Solutions


Solution 1 - Ruby

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

Solution 2 - Ruby

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

Solution 3 - Ruby

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.

Solution 4 - Ruby

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

Solution 5 - Ruby

Try this:

module Util
module MyUtil


	
	def self.redondear_up(suma,cantidad, decimales=0)

		unless suma.present?
			return nil
		end
		
		
		if suma>0
			resultado= (suma.to_f/cantidad)
			return resultado.round(decimales)
		end
		

		return nil
		

	end

end	
end	

Solution 6 - Ruby

to truncate a decimal I've used the follow code:

<th><%#= sprintf("%0.01f",prom/total) %><!--1dec,aprox-->
    <% if prom == 0 or total == 0 %>
        N.E.
    <% else %>
        <%= Integer((prom/total).to_d*10)*0.1 %><!--1decimal,truncado-->
    <% end %>
        <%#= prom/total %>
</th>

If you want to truncate to 2 decimals, you should use Integr(a*100)*0.01

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSamView Question on Stackoverflow
Solution 1 - Rubyboulder_rubyView Answer on Stackoverflow
Solution 2 - RubyTheoView Answer on Stackoverflow
Solution 3 - RubysteenslagView Answer on Stackoverflow
Solution 4 - RubyAnwarView Answer on Stackoverflow
Solution 5 - RubyHalleyRiosView Answer on Stackoverflow
Solution 6 - RubyIvan Carrasco QuirozView Answer on Stackoverflow