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
.
Using the modulo ( % ) operator The % operator is an arithmetic operator that calculates and returns the remainder after the division of two numbers. If a number is divided by 1, the remainder will be the fractional part. So, using the modulo operator will give the fractional part of a float.
and with this standard, floating point numbers are represented in the form, s represents the sign of the number. When s=1, floating point number is negative and when s=0 it is positive. F represent the fraction (which is also called mantissa) and E is the exponent.
y=\{x\}. y={x}. For nonnegative real numbers, the fractional part is just the "part of the number after the decimal," e.g. { 3.64 } = 3.64 − ⌊ 3.64 ⌋ = 3.64 − 3 = 0.64.
$x = $x - floor($x)
$x = fmod($x, 1);
Here's a demo:
<?php $x = 25.3333; $x = fmod($x, 1); var_dump($x);
Should ouptut
double(0.3333)
Credit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With