简体   繁体   English

如何停止四舍五入到 5 (Wordpress) 的两位小数?

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

Problem:问题:
I need to display 2 decimal places without rounding.我需要显示 2 个小数位而不四舍五入。
So I tried the following codes, but all three code display the same result below:所以我尝试了以下代码,但所有三个代码都显示以下相同的结果:

6.84 -> 6.85 (it should display 6.84) 6.84 -> 6.85(它应该显示 6.84)
4.59 -> 4.59 (it works well) 4.59 -> 4.59(效果很好)
0.05 -> 0.05 (it works well) 0.05 -> 0.05(效果很好)

The problem is all the three codes always show decimal 4 to 5 (eg, 6.84 -> 6.85).问题是所有三个代码总是显示十进制 4 到 5(例如,6.84 -> 6.85)。
Other numbers have no problem.其他号码没有问题。
Would you please let me know how to display 6.84 instead of 6.85?你能告诉我如何显示 6.84 而不是 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. 谢谢你。

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

Try built-in function format number of PHP : number_format试试 PHP 的内置函数格式 number : number_format

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM