Percentage format using PHP

I would like to format 0.45 as 45%.

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

One thought http://php.net/manual/en/class.numberformatter.php . Is this the best way? Has anyone used it and can you set an example? Thanks

+6
source share
2 answers

Most likely you want round instead of floor . But otherwise, this would be the most β€œstandard” way to do this. Alternatively, you can use sprintf , for example:

sprintf("%.2f%%", $x * 100) , which will print the percentage value of $ x with two decimal precision points and a percent sign after that.

The shortest way to do this is with NumberFormatter :

 $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 just add one more line of code so as not to bring much benefit.

+34
source

You can also use the function.

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

and then use the following to display the result.

 percent($lab_fee) 
+2
source

All Articles