18

I wrote a function to add commas and zeros to a number if necessary, but I've gotten stuck at the modulus function. According to my PHP:

float(877.5) % 1 == 0 //true

Shouldn't 877.5 % 1 == 0.5?

Liftoff
  • 24,717
  • 13
  • 66
  • 119
  • 2
    `Operands of modulo are converted to integers (by stripping the decimal part) before processing. For floating-point modulo, see fmod(). ` [reference](http://php.net/manual/en/language.operators.arithmetic.php) . thanks for asking – Accountant م Aug 27 '17 at 19:18

2 Answers2

22

It's giving you the reminder of the division what you need is fmod,

fmodReturns the floating point remainder (modulo) of the division of the arguments

echo fmod(877.5, 1); // 0.5
Rikesh
  • 26,156
  • 14
  • 79
  • 87
  • 3
    So what's the difference between % and fmod exactly? Is it because it's a float that % does not work? – Liftoff Apr 23 '14 at 07:01
  • Odd, in google chrome inspector, if I type 33.3 % 1 it gives me the float return of 0.3 – Shannon Hochkins Mar 23 '15 at 21:24
  • @ShannonHochkins - Calculations in Web Consoles are powered by JavaScript, not PHP. If you run `(9.5 % 6)` through JavaScript and PHP, JavaScript will give the answer `3.5` and PHP will give the answer `3`. If you want `3.5` from PHP, you need to ask it: `fmod(9.5, 6)` – Rounin Jul 01 '22 at 14:39
1

No, the modulus operator tells you the remainder of the division. Anything divided by 1 does not have a remainder, so it yields 0.

Sterling Archer
  • 22,070
  • 18
  • 81
  • 118