3

I have a question regarding number formating in PHP. I have a variable called "average", which is simply an average of a few values. To make it clear I rounded the number to 2 decimal places. Now the problem is, that if the average is for example 2.90, it only shows 2.9. Is there any way of displaying 2 decimal places always? I though I could do it by multiplying the number by 100, rounding it to zero d.p. and then divide by 100 again, but that seems a bit overcomplicated if there is an easier way of doing it.

Jachym
  • 485
  • 9
  • 21
  • 1
    How are you rounding the number? You could just use number_format($number, 2, '.', ''); You could also use sprintf('%0.2f', $number); – joe42 Oct 08 '13 at 22:01
  • Possible duplicate of [How to round down to the nearest significant figure in php](http://stackoverflow.com/questions/5834537/how-to-round-down-to-the-nearest-significant-figure-in-php) – Don't Panic Jun 03 '16 at 16:10

2 Answers2

4

Maybe you can try the number_format(float $number [, int $decimals = 0 ])?

For more information, take a look at http://php.net/manual/en/function.number-format.php

crodie
  • 112
  • 1
  • 10
1

Format the output with printf

printf("%.1f", $num); // prints 1 decimal place
printf("%.2f", $num); // prints 2 decimal places
Chris
  • 94
  • 3