PHP show only significant (non-zero) decimals

2020-03-09 06:52发布

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.

标签: php numbers
11条回答
仙女界的扛把子
2楼-- · 2020-03-09 07:44

How about

preg_replace(/\\.$/,'.0',rtrim($value,'0'))
查看更多
爷的心禁止访问
3楼-- · 2020-03-09 07:45

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);

Demo:

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
查看更多
霸刀☆藐视天下
4楼-- · 2020-03-09 07:47

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):

printf('%s%% off', $value*1);

This outputs:

0.00  => 0% off
0.01  => 0.01% off
20.00 => 20% off
20.50 => 20.5% off
查看更多
戒情不戒烟
5楼-- · 2020-03-09 07:47

rtrim($value, "0") almost works. The problem with rtrim is that it leaves 9.000 as 9.

So just rtrim($value, "0.") and you're done.

查看更多
别忘想泡老子
6楼-- · 2020-03-09 07:51

A trailing zero is significant:

  • A value of 9.0 implies, that the real value is more than 8.9 and less than 9.1
  • A value of 9.00000 implies, that the real value is more than 8.99999 and less than 9.00001

Therefore, your requirement is quite unusual. That's the reason why no function exists to do what you want.

查看更多
登录 后发表回答