Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Modulo Decimal

How can i do modulo arithmetic with decimal value since PHP only can do modulo with integer?

Example case:

 echo 1.92 % 1000; // (int) 1, expected result should be 1.92

is there any library to do this correctly?

More info about this modulo arithmetic problem: https://bugs.php.net/bug.php?id=34399

like image 761
GusDeCooL Avatar asked Nov 26 '12 16:11

GusDeCooL


People also ask

How can I get 2 decimal places in PHP?

$twoDecNum = sprintf('%0.2f', round($number, 2)); The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding. Save this answer.

How does PHP calculate mod?

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

How check value is decimal or not in PHP?

The is_numeric() function in the PHP programming language is used to evaluate whether a value is a number or numeric string. Numeric strings contain any number of digits, optional signs such as + or -, an optional decimal, and an optional exponential. Therefore, +234.5e6 is a valid numeric string.

How do you round down in PHP?

The floor() function rounds a number DOWN to the nearest integer, if necessary, and returns the result. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a floating-point number, look at the round() function.


2 Answers

There is also a floating point fmod() function

echo fmod(1.92, 1000)
like image 93
Mark Baker Avatar answered Oct 04 '22 20:10

Mark Baker


http://php.net/manual/en/function.fmod.php

I think you wanted this one, this returns float result?

like image 42
Alvar FinSoft Soome Avatar answered Oct 04 '22 22:10

Alvar FinSoft Soome