How to divide by a float in PHP?

384

I need to determine if a given numberx is divisble byy in PHP, beingy 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!

186

Answer

Solution:

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 expressinga % 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, callingmod(0.08,0.05) will return0.03.

726

Answer

Solution:

You could multiply both numbers by 100.

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

People are also looking for solutions to the problem: php - Get a the complete text in the current URL after the question mark

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.