4

By calculating areas I have a number which I need to display in a strange way.

Always display 2 decimal places. Always round up the 2nd decimal place if the 3rd+ decimal places > 0.

Examples:

0.5 = 0.50
0.500003 = 0.51
0.96531 = 0.97
0.96231 = 0.97
0.8701 = 0.88

Is there a built in function to do this in PHP or do I need to write one?

4

2 Answers 2

11

To always round up you will want to use something like this:

$number = 0.8701;

echo ceil($number*100)/100;

// = 0.88
2
  • ceil only rounds in + meaning 12.011 will be rounded to 12.02
    – ied3vil
    Commented Apr 10, 2014 at 14:48
  • 6
    Yes, if you read the OP question that is what he has asked for. Always round up to 2 decimal places. Commented Apr 10, 2014 at 14:50
7

You can use 2 functions:

I've used both with success, and depending on what you're doing with the result, you may chose either of the above functions.

Later edit: If you want to only round up, you can use ceil() - http://www.php.net/manual/en/function.ceil.php + number format or round

echo round(ceil($number*100)/100,2);

As another user suggested earlier

2
  • 3
    Using the round function is not needed in this case as the division by 100 will format it to 2 decimal places. Ceil returns a whole integer. Commented Apr 10, 2014 at 15:15
  • the round() method will fail on a number with two decimals : echo round(ceil(1.12*100)/100, 2); # output 1.13
    – Julien
    Commented Feb 21, 2020 at 9:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.