Search code examples
phpnumber-formattingpercentage

How do I make NumberFormatter format a percent number without "reinterpreting" it?


Example code:

$fmt = new NumberFormatter('sv_SE', NumberFormatter::PERCENT);
var_dump($fmt->format(99.99));

Expected output:

string(9) "99,99 %"

Actual output:

string(9) "9 999 %"

Analysis:

I must be "missing something". I already have the percentage number (ninenty-nine point ninenty-nine) and all I want is to output it appropriately for the given language+locale combination. For example, in the USA, it is "99.99%" with a period for the decimal mark and no space between the percentage number and the percentage sign, and in Sweden, it's "99,99 %" with a comma for the decimal mark and a space between. There are probably numerous other rules in other locales/language which I just haven't encountered yet.

I do not want PHP to "further process" the number I'm feeding it in any way. It's already "done". No more processing needed.

I frankly don't even understand why PHP turns it into "9999" when it's clearly given as a float as 99.99...

Is there some kind of hidden option to turn off this "further processing" of the number?


Solution

  • NumberFormatter is assuming the number to be between 0-1 in your case 99.99/100 === 0.9999 therefore you could use it that ways :

    $fmt = new NumberFormatter('sv_SE', NumberFormatter::PERCENT);
    var_dump($fmt->format(99.99/100));
    

    From reading the documentation I highly doubt there is any other way.