00 Votes

PHP: Round number to two decimal places

Question by Compi | 2012-06-19 at 22:52

I want to shorten a decimal number to only two decimal places in PHP. Is there a good way to achieve that?

ReplyPositiveNegativeDateVotes
00 Votes

If you want to output the number, I suggest using the PHP function number_format, that you can use like this:

$num = 1.234567
echo number_format($num, 2, ',', '.');
// output: 1,23

The first parameter is the number, the second the number of decimal places, the third is the decimal separator (a comma in this case), and the fourth the thousands separator (a point here). The last two parameters can be omitted as well, but by using them we can define exactly whether we would like to use the Amercian or another spelling of numbers. Otherwise, this is decided by the system, we are running our script on.

However, if you want to write the rounded number in a variable, you can proceed as follows:

$num = 1.234567;
$num = floor($num*100)/100;
echo $num;
// output: 1,23

Then you can go on calculating with the rounded number in your script.
2012-06-22 at 16:26

ReplyPositive Negative
00 Votes

You can also work with sprintf, here's a quick example:

echo sprintf ("% 01.2f", $ num);

The function sprintf() is quite extensive and has numerous options.

In short, the first parameter is the format, the second is the number that you are passing. The f stands for a floating number, the 2 stands for the two decimal places.
2012-10-02 at 19:46

ReplyPositive Negative
Reply

Related Topics

PHP: Rounding Numbers

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.