PHP 仅显示有效(非零)小数
在 PHP(使用内置函数)中,我想用小数转换/格式化数字,以便仅显示非零小数。然而,我的另一个要求是,如果它是一个没有小数值的数字,我仍然想显示零。示例:
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()
有不同的目的,这些就是我能想到的一切...
再次,我想指出,我并不是在寻找您自制的解决方案,我'我正在寻找一种使用内部 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")
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...
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
我认为没有办法做到这一点。正则表达式可能是您最好的解决方案:
演示:
I don't think theres a way to do that. A regex is probably your best solution:
Demo:
如果您想要一个内置解决方案并且您使用的 PHP 版本高于 4.2,您可以尝试
floatval( )
:打印
但
打印
希望这有帮助。
If you want a built-in solution and you're using a PHP version later than 4.2 you could try
floatval()
:prints
but
prints
Hope this helps.
尝试这样
会显示“2”
try something like this
will display "2"
难道不应该吗?:
PHP preg_replace 语法是
Shouldn't it be?:
The PHP preg_replace syntax is
尾随零很重要:
因此,你的要求很不寻常。这就是为什么没有函数可以做你想做的事情的原因。
A trailing zero is significant:
Therefore, your requirement is quite unusual. That's the reason why no function exists to do what you want.
输出:
Output:
开箱即用是不可能的,因为您有两种不同的方式来处理浮动片段。您首先必须确定片段中有多少个非零数字,然后使用 sprintf 进行相应操作。
Out of the box that isn't possible because you have two different ways of treating the fragment of your floats. You'll first have to determine how many non-zero numbers there are in your fragment and then act accordingly with sprintf.
怎么样
How about
假设数字被编码为或转换为字符串,这是一种通用方法:
Assuming the number is encoded as or cast to a string, here's a general purpose approach:
我的解决方案是让 php 将其处理为数字(即 *1),然后将其视为字符串(我的示例我使用存储为小数点后两位的百分比):
此输出:
My solution is to let php handle it as a number (is *1) and then treat it as a string (my example I was using percentages stored as a decimal with 2 decimal places):
This outputs:
所以只需 rtrim($value, "0.") 就可以了。
So just rtrim($value, "0.") and you're done.