When printing floats, ruby prints 1234.0
with only one 0
after the period. How can I force ruby to print two 0
s?
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.
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.
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.
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 ).
Format strings to the rescue:
>> puts "%.2f" % 1.0 #=> nil
1.00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With