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?
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.
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.
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.
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]
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
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