PHP convert decimal into fraction and back?

前端 未结 14 793
面向向阳花
面向向阳花 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:07

    You'll have to face a serious problem, because floats are not precise enough.

    When you'll have to deal with 1.3333, PHP will make an estimate of this value... So you will never be able to convert it to 1 1/3.

    It seems to be simple to overcome, but if you want your program to differentiate 1/7901 (~ 1,2656625743576762435134793064169e-4) with 1/7907 (~ 1,2647021626406981155937776653598e-4) precisely... this will be a real hell !!

    IMHO, if you want to deal with maths, you should rely on an external library... or try to make PHP communicate with Matlab.

    If you want to know more, i suggest you dig in floating point problems... Starting with wikipedia.

提交回复
热议问题