Remove useless zero digits from decimals in PHP

2019-08-16 02:30发布

I'm trying to find a fast way to remove zero decimals from number values like this:

echo cleanNumber('125.00');
// 125

echo cleanNumber('966.70');
// 966.7

echo cleanNumber(844.011);
// 844.011

Does exists some optimized way to do that?

21条回答
Juvenile、少年°
2楼-- · 2019-08-16 03:07

This Code will remove zero after point and will return only two decimal digits.

$number=1200.0000;
str_replace('.00', '',number_format($number, 2, '.', ''));

Output will be: 1200

查看更多
叛逆
3楼-- · 2019-08-16 03:08

$num + 0 does the trick.

echo 125.00 + 0; // 125
echo '125.00' + 0; // 125
echo 966.70 + 0; // 966.7

Internally, this is equivalent to casting to float with (float)$num or floatval($num) but I find it simpler.

查看更多
Rolldiameter
4楼-- · 2019-08-16 03:08

you could just use the floatval function

echo floatval('125.00');
// 125

echo floatval('966.70');
// 966.7

echo floatval('844.011');
// 844.011
查看更多
够拽才男人
5楼-- · 2019-08-16 03:09

Typecast to a float.

$int = 4.324000;
$int = (float) $int;
查看更多
在下西门庆
6楼-- · 2019-08-16 03:13

For everyone coming to this site having the same problem with commata instead, change:

$num = number_format($value, 1, ',', '');

to:

$num = str_replace(',0', '', number_format($value, 1, ',', '')); // e.g. 100,0 becomes 100


If there are two zeros to be removed, then change to:

$num = str_replace(',00', '', number_format($value, 2, ',', '')); // e.g. 100,00 becomes 100

More here: PHP number: decimal point visible only if needed

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-08-16 03:17
$str = 15.00;
$str2 = 14.70;
echo rtrim(rtrim(strval($str), "0"), "."); //15
echo rtrim(rtrim(strval($str2), "0"), "."); //14.7
查看更多
登录 后发表回答