skip to Main Content

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.

2

Answers


  1. Try built-in function format number of PHP : number_format

    $save_price_show = number_format($save_price, 2, ‘.’, ”)

    Login or Signup to reply.
  2. 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);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search