PHP 仅显示有效(非零)小数 [英] PHP show only significant (non-zero) decimals

查看:78
本文介绍了PHP 仅显示有效(非零)小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP(使用内置函数)中,我想用十进制转换/格式化一个数字,以便只显示非零小数.但是,我的另一个要求是,如果它是一个没有十进制值的数字,我仍然想显示零.示例:

In PHP (using built-in functions) I'd like to convert/format a number with decimal, so that only the non-zero decimals show. However, another requirement of mine is that if it's a number without a decimal value, I'd still like to show that zero. Examples:

9.000 -> 9.0
9.100 -> 9.1
9.120 -> 9.12
9.123 -> 9.123

rtrim($value, "0") 几乎可以工作.rtrim 的问题在于它将 9.000 保留为 9..sprintf() 看起来像是一个候选,但我无法让它具有可变数量的小数.number_format() 有不同的用途,我只能想到这些……

rtrim($value, "0") almost works. The problem with rtrim is that it leaves 9.000 as 9.. sprintf() seemed like a candidate, but I couldn't get it to have a variable amount of decimals. number_format() serves a different purpose, and those were all I could come up with...

再次,我想指出我不是在寻找您自制的解决方案,我正在寻找一种使用内部 PHP 功能来完成此任务的方法.我可以自己编写一个可以轻松完成此操作的函数,因此请保留这样的答案.

Again, I'd like to point out that I am not looking for your homemade solutions to this, I'm looking for a way to accomplish this using internal PHP functionality. I can write a function that will accomplish this easily myself, so hold answers like that.

推荐答案

我认为没有办法做到这一点.正则表达式可能是您最好的解决方案:

I don't think theres a way to do that. A regex is probably your best solution:

$value = preg_replace('/(\.[0-9]+?)0*$/', '$1', $value);

演示:

php> $a = array('0.000', '0.0001', '0.0101', '9.000', '9.100', '9.120', '9.123');
php> foreach($a as $b) { echo $b . ' => ' . preg_replace('/(\.[0-9]+?)0*$/', '$1', $b)."\n"; }
0.000 => 0.0
0.0001 => 0.0001
0.0101 => 0.0101
9.000 => 9.0
9.100 => 9.1
9.120 => 9.12
9.123 => 9.123

这篇关于PHP 仅显示有效(非零)小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆