简体   繁体   中英

PHP quantity formatting without trailing zero

I have a project in yii. But the question could be more to PHP then yii specific.

I have column quantity where user can input decimals or whole number. The thing is my client does not like to see the trailing zero. For example:

Item   |  Quantity
-------------------
Apple  |        10
Mango  |     1.000
Sugar  |      10,5
Flour  | 10.002,55

Currently, I am having two options,

  1. If using number_format, the result would be
Item   |  Quantity
-------------------
Apple  |        10,00
Mango  |     1.000,00
Sugar  |        10,50
Flour  |    10.002,55

This is the one that my client does not like.

  1. If + 0, the result would be
Item   |  Quantity
-------------------
Apple  |        10
Mango  |      1000
Sugar  |      10,5
Flour  |  10002,55

Difficult to see the thousands number.

How to do it on PHP to get the first table?

Thank you for your help in advance.

You can do it with a regex:

$values = array(10, 1000, 10.5, 10002.55);
foreach ($values as $val)
{
    $numberA = Yii::app()->numberFormatter->format('#,##0.00', $val);
    $numberB = preg_replace('/,00|(,[1-9])0/', '\\1', $numberA);
    printf('%s => %s<br />', $numberA, $numberB);
}

number_format allows you to specify the amount of decimals, then see if last 2 a zero's with the separator.

If they exist then remove them.

try

$num = 10002.00;
$var = number_format($num, 2, ',', '.');

if (substr($var, -3) == ",00")
    $var = substr($var, 0, -3);

echo $var;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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