PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 7, 2022

[FIXED] How to stop two decimal places rounding 4 to 5 (Wordpress)?

 August 07, 2022     decimal, php, rounding, woocommerce, wordpress     No comments   

Issue

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.

Solution

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);


Answered By - Mòe
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing