Home > front end >  How to stop two decimal places rounding 4 to 5 (Wordpress)?
How to stop two decimal places rounding 4 to 5 (Wordpress)?

Time:11-11

Problem:
I need to display 2 decimal places without rounding.
So I tried the following codes, but all three code display the same result below:

6.84 -> 6.85 (it should display 6.84)
4.59 -> 4.59 (it works well)
0.05 -> 0.05 (it works well)

The problem is all the three codes always show decimal 4 to 5 (eg, 6.84 -> 6.85).
Other numbers have no problem.
Would you please let me know how to display 6.84 instead of 6.85?


Code I tried:
$save_price = $original_price - $sale_price;
$save_price_show = intval(($save_price*100))/100;
echo $save_price_show

$save_price = $original_price - $sale_price;
$save_price_show = 0.01 * (int)($save_price*100);
echo $save_price_show

$save_price = $original_price - $sale_price;
$save_price_show = floor(($save_price*100))/100;
echo $save_price_show

Thank you.

CodePudding user response:

Try built-in function format number of PHP : number_format

$save_price_show = number_format($save_price, 2, '.', '')

CodePudding user response:

Use custom function

function numberPrecision($number, $decimals = 0)
{
    $negation = ($number < 0) ? (-1) : 1;
    $coefficient = 10 ** $decimals;
    return $negation * floor((string)(abs($number) * $coefficient)) / $coefficient;
}

numberPrecision($save_price, 2);
  • Related