Hi all,

How to convert the fractions into decimals and vice versa in php.

I have a form, where the user will enter fractions in the text boxes such as "1 1/2", "1 1/4" and so on. I need to store all these values in mysql database after converting it into decimal value, and again fetch the value from database and re-convert it into fractions and display it to the user in a different php page. So what is best solution for this.

Can anyone give some hints.

With regards,

Don't know WHY you're doing this conversion if there's no calculations on it, just store it as a string and call it back! If you are doing calculations...

Well The servant posted some info, but i'd like to attack this problem the old fashion way.

For example I get the string "1 1/4" and want 1.25 stored in DB.

You explode() on space. You'll have "1" and "1/4" in an array.

Then explode() "1/4" on "/" OR "\" (or both to be safe?).

Then you'll have 3 numbers 1, 1, and 4.

You get float value of 1/4, which should give you 0.25 in a variable. then add the 1 left over, and you'll have 1.25.

(I should have given you the code vs logic, must faster, but alas, you learn as you do)

for converting back. You explode() on what???? if you said period "." you are Correct!

you'll have "1", and "25" in an array. THEN you must find out how many characters in this second string, in this case 2.

If its 1, you must put it over 10, if its 2, you must divide (denomenator) is 100.

In this case it would be 100. Logically now we have "1 25/100".... almost there but not quite.

We find the greatest common divisor using the handy dandy php function gmp_gcd("25","100"), which should output 25!

Dividie both numerator and denomeator by that value and should get an integer.

What integers!??? 1 and 4 silly!!

There you have it, 1, 1, 4, which you could display as "1 1/4" in a string!

VOILA!

basic freshman math!

Cheerio!

DM