How to delete trailing zeros after the 3rd decimal place in PHP?

我怕爱的太早我们不能终老 提交于 2019-12-11 19:20:34

问题


thanks in advance.

I have a WP WooCommerce store and need to upload some prices that have 3 decimal places, e.g. £0.012 (products that are purchased in volumes of 000s).

The majority of my products are 'ordinary' with 2 decimal places.

There is a function in WooCommerce that allows for 3 decimal places - fine. Also a function to delete trailing zeros, but it deletes them if it's an integer e.g. £10.00 becomes £10.

My problem arises when the 95% of 'ordinary' price products start showing £10.000 or £5.230.

In a nutshell I'm looking for a way to delete trailing zeros but ONLY after the 3 decimal place;

Retain - £0.012 Delete any 3rd decimal 0 on prices like £10.00 or £5.23

Does anyone have a good solution?

Thanks


回答1:


If you want to use regular expressions you can match them with

 (?<=\d{2})(0+)$

 preg_replace("/(?<=\d{2})(0+)$/", "", $price_string)

to match all zeroes which come after at least two digits. (It will match the zeroes in parenthesis):

12.002(0)
12.00(0000)
12.01(000000)
12.232(0)
12.123



回答2:


an if else statement would probably work, unless you also have prices like 10.001:

$price = '0.001';

if ($price < 1) {
    // don't round
} else {
    $price = number_format($price, 2);
}

or just

$price = ( $price < 1 ) ? $price : number_format($price, 2) ;



回答3:


Why not just something like this ↓ ?

$numberAsString = number_format($yourUglyNumber, 2, '.', ' ');

PHP function number_format


If you get the number as string with the money sign, you can first filter this out:

$moneyString = "£300.4578525";

// remove all non-numeric and cast to number
$moneyNum = preg_replace("/[^0-9.]/", "", $moneyString) + 0;

// format
$formatted = number_format($moneyNum, 2, '.', ' ');

// add the money symbol if you want
$formatted = '£' + $formatted.


来源:https://stackoverflow.com/questions/18021111/how-to-delete-trailing-zeros-after-the-3rd-decimal-place-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!