'how to prevent float variables displaying as scientific notation when printing [duplicate]

I am using "(float)$val" for some calculation, but for some decimal value like -0.00000025478625 (float)-0.00000025478625 is resulting to -2.5479E-70, i need the value same as that of -0.00000025478625, without affecting other scenarios. how to prevent this conversion ?



Solution 1:[1]

This is the scientific notation of float number. So, if you want to format then you should use number_format() function. Below example the second parameter will tell at what precision do you need. So, as per your example you should use 14.

Try this:

$var = number_format((float)-0.00000025478625, 14);
print($var);

Solution 2:[2]

I think you misunderstand the representation of your float. The value -2.5479E-70 actually is still a float value in scientific representation.

What this actually means is that your value is very small, so for readability reasons it is represented in this format. To read it you may replace the E with an multiplication of the following number to the power of 10 -2.5479 * 10^(-70). So this means that your floating point number is prepended with 70 zeros (which I wont write down here).

As example -5.47E-4 would be -5.47 * 10^(-4) which is the same as -5.47/10000 resulting in -0.000547.

Also, for printing your value was rounded. Internally it still uses the exact value. So if you use this number in further evaluations you do not lose any accuracy.

Solution 3:[3]

Something to add to Manish's answer.

Please note that floating point numbers in PHP have limited precision:

enter image description here

For example:

<?php

echo number_format((float) 0.0000000000000000000000004, 50);

or even

<?php

printf('%f15.50', (float) 0.0000000000000000000000004);

You'd get something like this (depends on the system):

0.00000000000000000000000040000000000000001539794790

which is not exactly the original floating point number to print.

You can never count on the accuracy of floating point number. The best way to deal with them is to always store them as string until you need some calculation done.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Manish Kumar
Solution 2 Handfeger
Solution 3