7

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()?

4 Answers 4

13

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

Sign up to request clarification or add additional context in comments.

2 Comments

I would not recommend this solution.. For 50 it returns 5 for example.. You need to do this, if number without decimal point can occur: \str_contains($number, '.') ? \rtrim(\rtrim($number, '0'), '.') : $number;
I would not recommend either! number_format() returns a string. It might work in this case but if the number is above 1000, it will cause issues. Let's say you have a number 1234.56, number_format() will return "1,234.56" and if you attempt to convert it to float, the result will be 1.0.. so no good.
3

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 will be 50.23.

Unless you specify at which point to round up or down, it won't change your decimal values. So just use default round()

1 Comment

This works, removes trailing decimal zeros, however it does not format the number to have comma separation.
1

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

Comments

0

This function works with PHP 8 and above, or requires a polyfill for the str_contains() function.

function sanitize_float($value): string
{
    $value = (string) $value;
    if (str_contains($value, '.')) {
        $value = rtrim(rtrim((string) $value, '0'), '.');
    }

    return $value;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.