Several common ways of handling numbers and decimals in PHP code

user:visitors Date:2024-11-15 23:25:0350

When using PHP to perform some operations, sometimes the operation is followed by an endless loop or no loop decimal, which affects the display or calculation of the operation result, so how to do some simple processing of these decimals?

1. Convert directly to an integer and discard the value after the decimal point

<?php

$xiaoshu ="3.1875";

$fistcx=strpos($xiaoshu,".");

echo substr($str,0,$fistcx);

?>

First of all, assuming that the decimal is 3.1875, first find "." and then use the substr function to intercept from the first bit. The integer part of the decimal number can be obtained.

<?php

$xiaoshu ="3.1875";

echo intval($xiaoshu);

?>

The intval function in PHP can directly round decimals.

2. Round up

<?php

$xiaoshu2 ="1.1379";

$xiaoshu2 ="1.1579";

echo ceil($xiaoshu2);

?>

The ceil function can be rounded upwards, i.e. there is a decimal direct integer part of the result of +1.

3. Round downward

<?php

$xiaoshu3 ="5.135";

$xiaoshu3 ="6.14766";

echo floor($xiaoshu3);

?>

The value obtained by using the floor function is infinitely 0 for the positive integer part, that is, the integer is added to 1 and subtracted by 1, and the negative part is infinitely small.

4. Rounding

<?php

$xiaoshu4 ="6.133553";

$xiaoshu4 ="3.7682";

echo round($xiaoshu4,2);

echo sprintf("%.2f",$xiaoshu4);

echo number_format($xiaoshu4, 2); //10.46

?>

The first parameter of the round function is a numeric value, and the second parameter is the number of digits. Or sprintf directly format strings, thousands of groups to format the function of numbers

5. Keep the decimal place of the specified number of digits

<?php

$weishu="3";

$xyqzxs="87.12137";

$cws=pow(10,$weishu);

echo intval(($xyqzxs*$cws))/$cws;

echo ceil(($xyqzxs*$cws))/$cws;

echo floor(($xyqzxs*$cws))/$cws;

?>

First, define a variable to store the number of decimal places that need to be calculated, here set to 3, then define the exact value of the decimal 87.12137, and obtain the value of 10 to the power of N digits through the pow function, which is used to convert the decimal to an integer and remove the decimal number after the specified number of digits, so as to retain the decimal number of digits that need to be retained.

Combined with the above processing methods for integer parts, we use intval(), ceil(), and floor() to process the integer part respectively, and then divide it by the Nth power conversion value used to keep the decimal 10 before, and turn the integer part into a decimal again, we can get the decimal of the specified number of digits or the decimal up and down decimal three different answers.

Popular articles
latest article