Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby float with double 0

When printing floats, ruby prints 1234.0 with only one 0 after the period. How can I force ruby to print two 0s?

like image 598
trnc Avatar asked Apr 18 '11 12:04

trnc


People also ask

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 make a float in Ruby?

The to_f function in Ruby converts the value of the number as a float. If it does not fit in float, then it returns infinity. Parameter: The function takes the integer which is to be converted to float. Return Value: The function returns the float value of the number.

Does Ruby have double?

Ruby inherently does not support "Double dispatch". We will see how to get around that issue shortly. First let's see an example in Java which support Double dispatch. Java supports method overloading which allows two methods with same name to differ only in the type of argument it receives.

Does Ruby have floats?

In other words, a float in a Ruby program is a number that contains a decimal point. Ruby will consider any number written without decimals as an integer (as in 138 ) and any number written with decimals as a float (as in 138.0 ).


1 Answers

Format strings to the rescue:

>> puts "%.2f" % 1.0 #=> nil
1.00
like image 89
Michael Kohl Avatar answered Oct 31 '22 21:10

Michael Kohl