phpnumberformatter

NumberFormatter to leave always 2 digits behind floating point


I have ended up with a little bit of an overkill here, but I just cannot seem how to nail it:

$formatter = new NumberFormatter('lv_LV', NumberFormatter::DECIMAL);

$formatter->setAttribute(NumberFormatter::FRACTION_DIGITS, 2);
$formatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, 2);
$formatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, 2);
$formatter->setAttribute(NumberFormatter::DECIMAL_ALWAYS_SHOWN, 2);

What I am trying to achieve here is:

+-------+--------+----------+-------+
| INPUT | ACTUAL | EXPECTED | VALID |
+-------+--------+----------+-------+
|  5,77 |   5.77 |     5.77 | YES   |
|  5,20 |    5.2 |     5.20 | NO    |
|  5,00 |      5 |     5.00 | NO    |
|     0 |      0 |     0.00 | NO    |
+-------+--------+----------+-------+

In short, I always want 2 digits behind the floating point.

How do I achieve this with PHP's NumberFormatter?


Solution

  • You should use http://php.net/manual/en/function.number-format.php

    $var = number_format(553,2);
    echo $var
    

    Where 553 is the number and 2 is the amount of decimal places to display. It will ouput

    553,00

    NumberFormatter has a way of dealing with currencies if this is what you are after http://php.net/manual/en/function.money-format.php