0

Not sure if this is normal but personally, I think it is not giving me the right result. Lets look at this example

$a = 3.32475;
$b = round($a,2,PHP_ROUND_HALF_UP);

I was expecting 3.33 but instead I get 3.32. Am I missing something here? Is the rounding function only literally uses the 3rd decimal point value instead of the whole value, and then rounding it up?

What I was expecting was something like this:-

 - 3.32475
 - 3.3248
 - 3.325
 - 3.33

Am I doing something wrong here? is there a better way for me to get an accurate rounding base on the whole value rather than the 3rd decimal point?

Thanks.

asyadiqin
  • 1,637
  • 3
  • 19
  • 25
  • Just a brief history... I have those fancy calculator that allows me to set the answer from 0 to 3 decimal points or full value. What I did was to get 2.5% of 132.99. On the full setting, it came out as 3.32475 but on 2 decimal points, it came out as 3.33. That is why I posted this question as to why I cannot get the same result with PHP round(). – asyadiqin Jun 19 '16 at 14:02

1 Answers1

1

It would round up to 3.33 anything >= 3.325. Your value is less than that, so it rounds down to 3.32.

As stated in the docs, PHP_ROUND_HALF_UP means:

Round val up to precision decimal places away from zero, when it is half way there. Making 1.5 into 2 and -1.5 into -2. [Emphasis added]

If you want to force it to "round" up, use ceil() instead of round():

$a = 3.32475;
$b = ceil($a * 100) / 100;

This finds the "ceiling" value of 332.475, i.e., 333, then divides that by 100 to give 3.33.

Also, be aware that rounding never actually works the way you described (rounding digits one at a time) unless you write a special routine to do that (and I can't think of any real-world reason you would want to do so).

elixenide
  • 44,308
  • 16
  • 74
  • 100
  • It does work on that value but try it on 3.392727. My fancy calculator returns a value of 3.39, while using your answer returns me 3.40 – asyadiqin Jun 19 '16 at 14:52
  • @asyadiqin Not sure what you mean. What does your calculator have to do with how PHP works? Also, please note that `ceil` is *not* another name for `round`. – elixenide Jun 19 '16 at 14:53
  • My apologies ... Maybe I can explain it better. My issue is because the persons using my function will normally check using their fancy calculator. So I need to be able to provide an exact result. – asyadiqin Jun 19 '16 at 14:58
  • @asyadiqin Again, I'm not sure what you're asking. This *is* an exact result, and it is 100% predictable and consistent. I answered your question (how to make the number round everything up at a certain significant digit). If you're trying to reproduce some other result from a calculator, you need to be more precise and ask a new question. Also, be aware that rounding never actually works the way you described (rounding digits one at a time) unless you write a special routine to do that. – elixenide Jun 19 '16 at 15:05