We help IT Professionals succeed at work.

Modulus but not full ints

tonelm54
tonelm54 asked
on
Im trying to figure out how to modulus with decimal places.
$totTime = 1;
$modDivisor = 3 * 0.25;

echo "Total Time: " . $totTime . "<br/>";
echo "Divosor: " . $modDivisor . "<br/>";
echo $totTime % $modDivisor;

Open in new window


But keep getting

FATAL ERROR Uncaught DivisionByZeroError: Modulo by zero in /home4/phptest/public_html/code.php70(5) : eval()'d code:7 Stack trace: #0 /home4/phptest/public_html/code.php70(5): eval() #1 {main} thrown on line number 7

The issue I have is the "3*0.25" can be "2*0.25" or "5*0.25" or any other number, so I cant multiply into full number

For example:-
php
$totTime = 1;
$modDivisor = 5 * 0.25;

echo "Total Time: " . $totTime . "<br/>";
echo "Divosor: " . $modDivisor . "<br/>";
echo $totTime % $modDivisor;

Open in new window


Should give 0.25, but instead gives 0

Any ideas?
Comment
Watch Question

Commented:
Use fmod(). The % operator is just for working with integers, so if you're working with decimals/floats, fmod() is the right function.

https://www.php.net/manual/en/function.fmod.php

echo fmod(totTime , $modDivisor);
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You could also do this
<?php
$totTime = 1;
$modDivisor = 5 * 25;

echo "Total Time: " . $totTime . "<br/>";
echo "Divosor: " . $modDivisor . "<br/>";
echo (($totTime*100) % $modDivisor)/100);

Open in new window


Just move the numbers into the integer domain by multiplying by 100