Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From Fraction to Decimal and Back?

Is it possible to store a fraction like 3/6 in a variable of some sort? When I try this it only stores the numbers before the /. I know that I can use 2 variables and divide them, but the input is from a single text field. Is this at all possible?

I want to do this because I need to calculate the fractions to decimal odds.

A bonus question ;) - Is there an easy way to calculate a decimal value to a fraction? Thanks..

like image 363
CC. Avatar asked Mar 15 '09 23:03

CC.


People also ask

What is 7/8 as a decimal?

7 divided by 8 or 7/8 is equal to 7 divided by 8, which is equal to 0.875.

What is 3/8 as a decimal?

3/8 as a decimal is 0.375. How to do the long division method?

What is 1/8 as a decimal?

To convert 1/8 to a decimal, divide the denominator into the numerator. 1 divided by 8 = . 125.

What is 5/8 as a decimal?

Answer and Explanation: As a decimal, 58 is 0.625.


2 Answers

Well in short, there is no true way to extract the original fraction out of a decimal.

Example: take 5/10

you will get 0.5

now, 0.5 also translates back to 1/2, 2/4, 3/6, etc.

Your best bet is to store each integer separately, and perform the calculation later on.

like image 157
John T Avatar answered Oct 16 '22 04:10

John T


The best thing to do is to implement a fraction class (or rational number class). Normally it would take a numerator and denominator and be able to provide a double, and do basic math with other fraction objects. It should also be able to parse and format fractions.

Rational Arithmetic on Rosetta Code looks like something good to start with.

like image 35
Lou Franco Avatar answered Oct 16 '22 04:10

Lou Franco