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

前端 未结 10 860
不思量自难忘°
不思量自难忘° 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:48
    $x = $x - floor($x)
    
    0 讨论(0)
  • 2020-11-30 05:48

    My PHP skills are lacking but you could minus the result of a floor from the original number

    0 讨论(0)
  • 2020-11-30 05:51

    You can use fmod function:

    $y = fmod($x, 1); //$x = 1.25 $y = 0.25
    
    0 讨论(0)
  • 2020-11-30 05:52

    However, if you are dealing with something like perlin noise or another graphical representation, the solution which was accepted is correct. It will give you the fractional part from the lower number.

    i.e:

    • .25 : 0 is integer below, fractional part is .25
    • -.25 : -1 is integer below, fractional part is .75

    With the other solutions, you will repeat 0 as integer below, and worse, you will get reversed fractional values for all negative numbers.

    0 讨论(0)
  • 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, '.' );
    
    0 讨论(0)
  • 2020-11-30 05:56

    The answer provided by nlucaroni will only work for positive numbers. A possible solution that works for both positive as well as negative numbers is:

    $x = $x - intval($x)
    
    0 讨论(0)
提交回复
热议问题