0

I'm trying to show one decimal place for rating number I have

but it returns unexpected value.

I used number_format and the round functions and both have the same issue, or i'm doing something wrong.

I tried to make this number show one decimal number

4.96 and it always returns 5 instead of 4.9

    number_format(4.96, 1)

    round(4.96, 1) 

    round(4.96, 1,PHP_ROUND_HALF_DOWN)

both functions returns 5 instead of 4.9

I searched all answers but couldn't find anything helpful.

Jared Forth
  • 1,577
  • 6
  • 17
  • 32
  • `4.96` is closer to `5.00` than it is to `4.90`, so the rounding is doing what it's told to - rounding to the nearest 1-decimal place, `5.0`. – Qirel Jul 23 '19 at 12:56
  • but mathematically speaking, 4.96, to 1dp is 5. – treyBake Jul 23 '19 at 12:56
  • what are you trying to accomplish? you want 1 decimal ? you want to round the second decimal? – Vidal Jul 23 '19 at 12:58

2 Answers2

1

Rounding 4.96 will round .9 up, so it will be 5 in all cases. If you want to do it without rounding, you may have to tweak it a bit to fool it:

floor(4.96 * 10) / 10;  // 4.9
aynber
  • 22,380
  • 8
  • 50
  • 63
1

Here's a function you can use to achieve this.

function convertToSingleDecimal($num, $precision = 2) {
return floor($num) . substr(str_replace(floor($num), '', $num), 0, $precision + 1);
}
  print convertToSingleDecimal("4.96", 1);
Rivers
  • 2,102
  • 1
  • 16
  • 27