-1

我一直在用 PHP 处理长数字。就像下面的例子。

12.020000
12.000000

为了摆脱尾随零和小数点,我一直在函数中使用以下内容。

return rtrim(rtrim($str, "0"),".");

所以上面的结果是这样的。

12.02
12

这有点短视,因为当1000进入时它会变成1.

有人可以帮我编写代码以仅删除小数点后的尾随零吗?

如果代码删除了小数位,则加分,但我总是可以将其输入rtim($str,".").

编辑:为了清楚起见,我只在显示到屏幕时删除小数位和零。也不能选择浮动,因为我也处理像 0.00000001 这样的数字,这些数字就像 1.0e-9 一样。

4

2 回答 2

5

你为什么用字符串来保存数字?让它浮动,它会解决你的问题。

$string = '12.020000';
$number = (float) $string; // will be 12.02

然后,如果您想将其用作字符串(但为什么呢?)

$string = (string) $number;
于 2013-10-10T12:14:51.483 回答
3

The thing that perplexes me about your question is that extra zeros won't be included in a number variable without intentionally adding them with number_format. (This may be why someone down-voted it).

Normally you don't want to use string functions (meant for text) on variables that hold numbers. If you want to round off a number, use a function like round.

http://php.net/manual/en/function.round.php

There's also number_format, which can format numbers by adding zero padding: (it doesn't actuall round, just trims off excess numbers).

http://php.net/manual/en/function.number-format.php

Since your zeros are appearing, it's likely that you simply need to multiple the variable by 1, which will essentially convert a string to a number.

Good luck!

于 2013-10-10T12:19:12.327 回答