PHP convert decimal into fraction and back?

前端 未结 14 973
面向向阳花
面向向阳花 2020-12-05 07:43

I want the user to be able to type in a fraction like:

 1/2
 2 1/4
 3

And convert it into its corresponding decimal, to be saved in MySQL,

14条回答
  •  盖世英雄少女心
    2020-12-05 08:02

    A variation of Jir's approach could actually work if only a limited amount of denominators are used : multiply everything by the least common denominators (and round the result to discard any remaining decimals due to approximation).

    I.e.: if you only have to deal with halfs, thrids and quarters, just multiply everything by 12.

    And also if you know the common denominator, this should greatly reduce the search speed by knowing exactly which numbers to search instead of searching all n+1 possible.

    If you have to deal with lots of unusual fractions, like 1/7, 1/13, etc. well, stick to Derek's solution and store the original value too.

提交回复
热议问题