federicot
federicot

Reputation: 12341

How to divide by a float in PHP?

I need to determine if a given number x is divisble by y in PHP, being y a float, specifically 0.05.

But when I do it,

if ($number % 0.05 === 0) {
    // Continue
}

I recieve the following PHP warning:

Division by zero

What can I do to solve this? Thanks!

Upvotes: 2

Views: 137

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324750

The definision of modulus is as follows:

In computing, the modulo (sometimes called modulus) operation finds the remainder of division of one number by another.

Another way of expressing a % b is: a - b * floor(a/b)

Therefore, you could define your own function:

function mod($a,$b) {return $a-$b*floor($a/$b);}

And simply call it. For example, calling mod(0.08,0.05) will return 0.03.

Upvotes: 6

WhoaItsAFactorial
WhoaItsAFactorial

Reputation: 3558

You could multiply both numbers by 100.

if (($number * 100) % 5 === 0) {
    // Continue
}

Upvotes: 0

Related Questions