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
Reply
Related Topics
Delphi/Lazarus: 3 Ways to round a Number to X Decimal Places
Tutorial | 7 Comments
PHP: Rounding Numbers
Tutorial | 0 Comments
Delphi/Lazarus: Function to Round Number to any Position after or before Decimal Point
Tutorial | 0 Comments
Delphi/Lazarus: Round Decimal Numbers up, down and normally
Tip | 0 Comments
Delphi/Lazarus: Round Number to the next 10, 100 or 1000
Question | 1 Answer
Delphi/Lazarus: Only allow Numbers in TEdit
Tip | 0 Comments
German Tax Declaration: Round up or down?
Question | 1 Answer
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.
If you want to output the number, I suggest using the PHP function number_format, that you can use like this:
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:
Then you can go on calculating with the rounded number in your script.
2012-06-22 at 16:26
You can also work with sprintf, here's a quick example:
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