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条回答
你好瞎i
2楼-- · 2019-08-16 02:55

Complicated way but works:

$num = '125.0100';
$index = $num[strlen($num)-1];
$i = strlen($num)-1;
while($index == '0') {
   if ($num[$i] == '0') {
     $num[$i] = '';
     $i--;
   }

   $index = $num[$i];
}

//remove dot if no numbers exist after dot
$explode = explode('.', $num);
if (isset($explode[1]) && intval($explode[1]) <= 0) {
   $num = intval($explode[0]);
}

echo $num; //125.01

the solutions above are the optimal way but in case you want to have your own you could use this. What this algorithm does it starts at the end of string and checks if its 0, if it is it sets to empty string and then goes to the next character from back untill the last character is > 0

查看更多
混吃等死
3楼-- · 2019-08-16 03:00
$x = '100.10'; 
$x = preg_replace("/\.?0*$/",'',$x); 
echo $x;

There is nothing that can't be fixed with a simple regex ;)

http://xkcd.com/208/

查看更多
贪生不怕死
4楼-- · 2019-08-16 03:01

This is my solution. I want to keep ability to add thousands separator

    $precision = 5;    
    $number = round($number, $precision);
    $decimals = strlen(substr(strrchr($number, '.'), 1));
    return number_format($number, $precision, '.', ',');
查看更多
Animai°情兽
5楼-- · 2019-08-16 03:04

If you want to remove the zero digits just before to display on the page or template.

You can use the sprintf() function

sprintf('%g','125.00');
//125

‌‌sprintf('%g','966.70');
//966.7

‌‌‌‌sprintf('%g',844.011);
//844.011
查看更多
Ridiculous、
6楼-- · 2019-08-16 03:04

Strange, when I get a number out of database with a "float" type and if my number is ex. 10000 when I floatval it, it becomes 1.

$number = $ad['price_month']; // 1000 from the database with a float type
echo floatval($number);
Result : 1

I've tested all the solutions above but didn't work.

查看更多
一夜七次
7楼-- · 2019-08-16 03:06
$value = preg_replace('~\.0+$~','',$value);
查看更多
登录 后发表回答