I am trying to get a fraction part of a decimal number in rails. For example I have a number, that "1.23" and I want to get "23" It is may be too easy but, does anyone have any idea about how can I do?
Using the modulo ( % ) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.
It should be noted that 3/4 and 75/100 are equivalent fractions. The value of 0.75 as a fraction is 3/4.
Solution: 1.75 as a fraction is 7/4.
The first digit after the decimal represents the tenths place. The next digit after the decimal represents the hundredths place. The remaining digits continue to fill in the place values until there are no digits left.
Try to use modulo method:
1.23.modulo(1) => 0.23
Read more here: http://www.ruby-doc.org/core-1.9.3/Numeric.html#method-i-modulo
Or you can convert float to integer and substract it from original float value.
1.23 - 1.23.to_i => 0.23
I am not sure if it is the easiest way to do it - but you can simply split the number using "." character - like this:
number = 1.23 parts = number.to_s.split(".") result = parts.count > 1 ? parts[1].to_s : 0
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