简体   繁体   English

PHP数量格式化,不尾随零

[英]PHP quantity formatting without trailing zero

I have a project in yii. 我在yii中有一个项目。 But the question could be more to PHP then yii specific. 但是问题可能更多是PHP,而不是yii。

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 如果使用number_format,结果将是
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 如果+ 0,结果将是
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? 如何在PHP上获得第一张表?

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. number_format允许您指定小数位数,然后使用分隔符查看最后2个数字是否为零。

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;

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

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