21

I would like to format 0.45 as 45%.

I know I can just do something like FLOOR($x*100).'%', but wonder if there is a better way (better is defined as more standard and not necessarily faster).

One thought is http://php.net/manual/en/class.numberformatter.php. Is this a better way? Has anyone used it and can you show an example? Thanks

user1032531
  • 24,767
  • 68
  • 217
  • 387

2 Answers2

58

Most likely, you want round instead of floor. But otherwise, that would be the most "standard" way to do it. Alternatively you could use sprintf such as:

sprintf("%.2f%%", $x * 100) which would print the percentage of $x with two decimal points of precision, and a percentage sign afterwards.

The shortest way to do this via NumberFormatter is:

$formatter = new NumberFormatter('en_US', NumberFormatter::PERCENT);
print $formatter->format(.45);

It would be better to do this if your application supports various locales, but otherwise you're just adding another line of code for not much benefit.

Colin M
  • 13,010
  • 3
  • 38
  • 58
  • 3
    Yes, round instead of floor. Have you tried using numberformatter? – user1032531 Jan 25 '13 at 16:03
  • @user1032531 See revised answer – Colin M Jan 25 '13 at 16:06
  • Colin, thanks! Can you explain the **"%.2f%%"** portion or point me in the right direction to understand it better? Thanks again! – Mr. B Nov 05 '13 at 18:22
  • 4
    @ToddBenrud %.2f is a special format specifier. The "%" denotes the beginning of the format specifier, the "f" indicates that the output should be a float, and the ".2" indicates that it should have a precision of two decimal points. Because "%" specifies the beginning of the format, two percent signs must be used if you want to actually print a percent sign. Thus the ending %%. Additional detail here: http://php.net/manual/en/function.sprintf.php – Colin M Nov 06 '13 at 01:27
  • 2
    You may need to enable NumberFormatter in your php.ini by uncommenting this line: extension=ext/php_intl.dll See [this](https://stackoverflow.com/questions/30554177/fatal-error-class-numberformatter-not-found) SO question for more information. – SnapShot Sep 01 '18 at 01:48
6

You can also use a function.

function percent($number){
    return $number * 100 . '%';
}

and then use the following to display the result.

percent($lab_fee)
Mr. B
  • 2,677
  • 6
  • 32
  • 42