I'm trying to round up the prices to remove the unwanted decimals in the sum of all the prices.Below is the screenshot for example,
So I need to adjust the prices to remove .2
decimal from the total.I tried below solution, but its only working for one set of prices not for other.
<?php
$values = [436.4,207.3,87.3,218.2,196.4,54.6];
$final_array = $val_array = []; $sum = 0;
foreach($values as $v){
$sum += roundValue($v, 5);
$val_array[] = roundValue($v, 5);
}
function roundValue($number, $denominator = 1)
{
$x = $number * $denominator;
$x = floor($x);
$x = $x / $denominator;
return $x;
}
$final_array[] = ['sum' => $sum, 'rates' => $val_array];
var_dump($final_array);
?>
Please check this running example for first set of prices: first
Please check this running example for second set of prices: Second
and even tried with all these solutions below, nothing works for me:
round($number + 0.01) - 0.01;
round($number + 0.05) - 0.05;
floor($number*100)/100;
Any suggestions please?
What you're doing is juggling types.
Notice, that number_format
returns string. You are adding that string to integer (or float later), so php is implicitly casting that string to int/float.
What you want to do (probably) is to make your computations on floats/integers and at the end, when you'd like to display it - use number_format
.
I would advise to do some reading on types.
This will be a good start.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.