Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...