This can work: floor($number * 100) / 100
This can work: floor($number * 100) / 100
Unfortunately, none of the previous answers (including the accepted one) works for all possible inputs.
1) sprintf('%1.'.$precision.'f', $val)
Fails with a precision of 2 : 14.239 should return 14.23 (but in this case returns 14.24).
2) floatval(substr($val, 0, strpos(precision + 1))
Fails with a precision of 0 : 14 should return 14 (but in this case returns 1)
3) substr($val, 0, strrpos(precision))
Fails with a precision of 0 : -1 should return -1 (but in this case returns '-')
4) floor(precision)) / pow(10, $precision)
Although I used this one extensively, I recently discovered a flaw in it ; it fails for some values too. With a precision of 2 : 2.05 should return 2.05 (but in this case returns 2.04 !!)
So far the only way to pass all my tests is unfortunately to use string manipulation. My solution based on rationalboss one, is :
function floorDec(
precision = 2) {
if ($precision < 0) { $precision = 0; }
$numPointPosition = intval(strpos(
numPointPosition === 0) { //$val is an integer
return $val;
}
return floatval(substr(
numPointPosition + $precision + 1));
}
This function works with positive and negative numbers, as well as any precision needed.
Is it possible to force a variable to 2 decimal places (not display to 2 decimal places)?
eg. $newcostprice = round($currentcostprice * 1.1,2);
This is fine for say 5.877 (5.88) but not for say 5.8034 (5.8)
How do I do it so it's always 2 decimal places even if the 2nd (or both!) are "0"?
You can use number_format():
return number_format((float)$number, 2, '.', '');
Example:
$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00
This function returns a string.
Use round() (use if you are expecting a number in float format only, else use number_format() as an answer given by Codemwnci):
echo round(520.34345, 2); // 520.34
echo round(520.3, 2); // 520.3
echo round(520, 2); // 520
From the manual:
Description:
float round(float
precision = 0 [, int $mode = PHP_ROUND_HALF_UP ]]);
Returns the rounded value of
valto specifiedprecision(number of digits after the decimal point).precisioncan also be negative or zero (default).
...
Example #1
round()examples
<?php
echo round(3.4); // 3
echo round(3.5); // 4
echo round(3.6); // 4
echo round(3.6, 0); // 4
echo round(1.95583, 2); // 1.96
echo round(1241757, -3); // 1242000
echo round(5.045, 2); // 5.05
echo round(5.055, 2); // 5.06
?>
###Example #2 mode examples
<?php
echo round(9.5, 0, PHP_ROUND_HALF_UP); // 10
echo round(9.5, 0, PHP_ROUND_HALF_DOWN); // 9
echo round(9.5, 0, PHP_ROUND_HALF_EVEN); // 10
echo round(9.5, 0, PHP_ROUND_HALF_ODD); // 9
echo round(8.5, 0, PHP_ROUND_HALF_UP); // 9
echo round(8.5, 0, PHP_ROUND_HALF_DOWN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_EVEN); // 8
echo round(8.5, 0, PHP_ROUND_HALF_ODD); // 9
?>