Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split float into integer and decimals in Ruby

Tags:

ruby

If I have a float like 3.75, how can I split it into the integer 3 and the float 0.75?

Do I have to convert the float into a string, and then split the string by ".", and then convert the parts into integers and floats again, or is there a more elegant or "right" way to do this?

like image 968
Johan Hovda Avatar asked Feb 07 '12 09:02

Johan Hovda


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 split a float number?

You can do this by converting the number to a string using num2str() , splitting on the dot using strsplit() , then convert each part back to doubles using str2num() . Note the 16 in the call to num2str : by default only 4 decimal places are put in the string.

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.


2 Answers

You can use Numeric#divmod with argument 1 for this:

Returns an array containing the quotient and modulus obtained by dividing num by numeric.

a.divmod 1
=> [3, 0.75]

If you want to get precise value, this method is available for BigDecimal as well:

3.456.divmod 1
=> [3, 0.45599999999999996]

require 'bigdecimal'
div_mod = BigDecimal("3.456").divmod 1
[div_mod[0].to_i, div_mod[1].to_f]
=> [3, 0.456]
like image 112
Aliaksei Kliuchnikau Avatar answered Sep 20 '22 17:09

Aliaksei Kliuchnikau


As mentioned you can use 3.75.to_i to get the integer. An alternate way to get the remainder is using the % operator eg. 3.75 % 1

like image 38
tdf Avatar answered Sep 21 '22 17:09

tdf