What's the best way to get the fractional part of a float in PHP?

前端 未结 10 944
不思量自难忘°
不思量自难忘° 2020-11-30 05:45

How would you find the fractional part of a floating point number in PHP?

For example, if I have the value 1.25, I want to return 0.25.

10条回答
  •  被撕碎了的回忆
    2020-11-30 05:54

    Don't forget that you can't trust floating point arithmetic to be 100% accurate. If you're concerned about this, you'll want to look into the BCMath Arbitrary Precision Mathematics functions.

    $x = 22.732423423423432;
    $x = bcsub(abs($x),floor(abs($x)),20);
    

    You could also hack on the string yourself

    $x = 22.732423423423432;    
    $x = strstr ( $x, '.' );
    

提交回复
热议问题