Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get fraction part of a decimal number

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?

like image 311
yagmurdursun Avatar asked Sep 13 '12 12:09

yagmurdursun


People also ask

How do you extract a fractional part of a number?

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.

How do you turn 0.75 into a fraction?

It should be noted that 3/4 and 75/100 are equivalent fractions. The value of 0.75 as a fraction is 3/4.

How do you convert 1.75 into a fraction?

Solution: 1.75 as a fraction is 7/4.

How do you find the part of a decimal?

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.


2 Answers

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 
like image 81
Eugene Dorian Avatar answered Sep 24 '22 02:09

Eugene Dorian


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 
like image 31
EfratBlaier Avatar answered Sep 27 '22 02:09

EfratBlaier