0

My PHP script is generating this type of numbering in some cases when expected is decimal. How to fix it so that this problem does not happen in the future?

Number result: 1.0000789671421E+15

Expected number would be: 1.00

  • As in 1.00 quadrillion? Because that's what that number is. `1.00 * 10^15` – Sammitch Apr 23 '21 at 22:00
  • @Sammitch I would like to know how to fix this rounding bug. I expected the 1.00 result but instead came this crazy number. – Rafael Furtado Apr 23 '21 at 22:07
  • 1
    It's not a rounding bug, it's an alternate representation of a very large number. It is literally the equivalent of the integer `1000078967142100`. If it's supposed to be equivalent to `1` you've got other issues. – Sammitch Apr 23 '21 at 22:10
  • how to round to 2 decimal places? – Rafael Furtado Apr 23 '21 at 22:24
  • Does this answer your question? [Show a number to two decimal places](https://stackoverflow.com/questions/4483540/show-a-number-to-two-decimal-places) – Kerem Apr 24 '21 at 22:06

1 Answers1

1

You want 2 places after the comma in the exponential notation. You can use round for this when the power of ten is known. I'll choose another example to better show this.

$float = 1.1230789671421E+15;

$round1 = round($float,-13);

var_dump($round1);  //float(1.12E+15)

If the rounding should only be done for the output, this can be done with printf().

printf('%1.2e', $float);  //1.12e+15

If a certain relative accuracy is required regardless of the power of ten, this can be implemented as follows:

$float = 1.5670789671421E+12;

$round2 = (float)sprintf('%1.2e',$float);

printf('%1.6e',$round2);  //1.570000e+12
jspit
  • 7,276
  • 1
  • 9
  • 17