Search code examples
phpnumbers

PHP number_format with only minimum decimal digits


How to set minimum decimal digits but not maximum decimal digits. I tried with number_format but the results were unexpected.

<?php

echo number_format("1000000", 2) . "<br>";
echo number_format("1000000.6", 2) . "<br>";
echo number_format("1000000.63", 2) . "<br>";
echo number_format("1000000.68464", 2) . "<br>";

?>

Result:

1,000,000.00
1,000,000.60
1,000,000.63
1,000,000.68

Expected Result:

1,000,000.00
1,000,000.60
1,000,000.63
1,000,000.68464

How do I do this?


Solution

  • There’s a more advanced class called NumberFormatter which is part of the intl extension that supports both minimum and maximum, and you can just set the latter to a high number to achieve your expected results.

    $f = new NumberFormatter('en-US', NumberFormatter::DECIMAL);
    $f->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 2);
    $f->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 999);
    echo $f->format("1000000") . PHP_EOL;
    echo $f->format("1000000.6") . PHP_EOL;
    echo $f->format("1000000.63") . PHP_EOL;
    echo $f->format("1000000.68464") . PHP_EOL;
    

    Output:

    1,000,000.00
    1,000,000.60
    1,000,000.63
    1,000,000.68464
    

    Demo: https://3v4l.org/filso#v8.0.25