Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP float modulus not working

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?

like image 771
Liftoff Avatar asked Apr 23 '14 06:04

Liftoff


People also ask

How does modulus work in PHP?

Modulo is an integer operator, so it converts both the operands to integers before calculating the remainder. So, basically, modulo does integer division and then gives back whatever is left from the dividend. The sign of the value returned by a modulo operation is determined by the sign of the dividend.

How can I get mod in PHP?

The fmod() function returns the remainder (modulo) of x/y.

How do you use modulus operator?

In most programming languages, modulo is indicated with a percent sign. For example, "4 mod 2" or "4%2" returns 0, because 2 divides into 4 perfectly, without a remainder. "5%2", however, returns 1 because 1 is the remainder of 5 divided by 2 (2 divides into 5 2 times, with 1 left over).

Can you do modulus operations with decimal numbers?

modulo doesn't work with decimals because it only accepts integers. As discussed above, you can define another procedure to see if two numbers are divisible by each other.


2 Answers

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
like image 132
Rikesh Avatar answered Sep 23 '22 08:09

Rikesh


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

like image 40
Sterling Archer Avatar answered Sep 22 '22 08:09

Sterling Archer