Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format percentage using PHP

Tags:

php

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

like image 490
user1032531 Avatar asked Jan 25 '13 15:01

user1032531


People also ask

How many maximum parameters you can pass in Number_format function?

The number_format() function formats a number with grouped thousands. Note: This function supports one, two, or four parameters (not three).


2 Answers

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.

like image 164
Colin M Avatar answered Sep 17 '22 21:09

Colin M


You can also use a function.

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

and then use the following to display the result.

percent($lab_fee)
like image 27
Mr. B Avatar answered Sep 16 '22 21:09

Mr. B