Home > OS >  PHP number_format with only minimum decimal digits
PHP number_format with only minimum decimal digits

Time:11-10

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?

CodePudding user response:

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

CodePudding user response:

Simple function for that. You can custom function for your idea: string to use for decimal point,...

function number_format_min_precision($v, $minPrecision) {
 $curentPrecision = strlen(explode('.', $v)[1] ?? 0);
 if ($curentPrecision < $minPrecision) return number_format($v, $minPrecision);
  return $v;
}
echo number_format_min_precision('1000000', 2) . PHP_EOL;
echo number_format_min_precision('1000000.6', 2) . PHP_EOL;
echo number_format_min_precision('1000000.63', 2) . PHP_EOL;
echo number_format_min_precision('1000000.68464', 2) . PHP_EOL;

Results:

1,000,000.00
1,000,000.60
1000000.63
1000000.68464
  • Related