In ruby, I want to convert a float to an int if it's a whole number. For example
a = 1.0 b = 2.5 a.to_int_if_whole # => 1 b.to_int_if_whole # => 2.5
Basically I'm trying to avoid displaying ".0" on any number that doesn't have a decimal. I'm looking for an elegant (or built-in) way to do
def to_int_if_whole(float) (float % 1 == 0) ? float.to_i : float end
Ruby | Numeric round() function The round() is an inbuilt method in Ruby returns a number rounded to a number nearest to the given number with a precision of the given number of digits after the decimal point. In case the number of digits is not given, the default value is taken to be zero.
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.
One simple way to it would be:
class Float def prettify to_i == self ? to_i : self end end
That's because:
irb> 1.0 == 1 => true irb> 1 == 1.0 => true
Then you could do:
irb> 1.0.prettify => 1 irb> 1.5.prettify => 1.5
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