Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby round float to_int if whole number

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 
like image 839
Eric Wright Avatar asked Jul 03 '09 00:07

Eric Wright


People also ask

How do you round to the nearest whole number in Ruby?

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.

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 an integer 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.


Video Answer


1 Answers

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 
like image 142
Yehuda Katz Avatar answered Oct 11 '22 13:10

Yehuda Katz