简体   繁体   中英

number_format() php remove trailing zeros

Is there a way with number_format() to leave out decimal places if the number is not a float/decimal?

For example, I would like the following input/output combos:

50.8 => 50.8
50.23 => 50.23
50.0 => 50
50.00 => 50
50 => 50

Is there a way to do this with just a standard number_format() ?

You can add 0 to the formatted string. It will remove trailing zeros.

echo number_format(3.0, 1, ".", "") + 0; // 3

A Better Solution: The above solution fails to work for specific locales. So in that case, you can just type cast the number to float data type. Note: You might loose precision after type casting to float , bigger the number, more the chances of truncating the number.

echo (float) 3.0; // 3

Ultimate Solution: The only safe way is to use regex:

echo preg_replace("/\.?0+$/", "", 3.0); // 3
echo preg_replace("/\d+\.?\d*(\.?0+)/", "", 3.0); // 3

Snippet 1 DEMO

Snippet 2 DEMO

Snippet 3 DEMO

If you want to use whitespace here is better solution

function real_num ($num, $float)
{
    if (!is_numeric($num) OR is_nan($num)  ) return 0;

    $r = number_format($num, $float, '.', ' ');

    if (false !== strpos($r, '.'))
        $r = rtrim(rtrim($r, '0'), '.');

    return $r;
} 

Use:

$a = 50.00;

$a = round($a, 2);

Even though the number has 2 zeros trailing it, if you round it, it won't show the decimal places, unless they have some kind of value.

so 50.00 rounded using 2 places will be 50, BUT 50.23 it will be 50.23

Thank you, yes thank you. So EASYYYY.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM