When i make the following multiplication in PHP:
$ret = 1.0 * 0.000000001;
i get the result: 1.0E-9
I want to convert this result into the normal decimal notation, how can i do this?
sprintf('%f',$ret)
doesn't work, it returns 0.000000
. Overflow?
sprintf('%f',$ret)
doesn't work, it returns0.000000
. Overflow?
sprintf
works, however you miss some point here.
0.000000
is not overflow. It's just that sprintf
for the %f
modifier uses 6 digits per default. Also please take care that %f
is locale aware, %F
is probably better suited.
You might want to use more digits, e.g. let's say 4 000 000 (four million):
$ php -r "printf('%.4000000F', 1*0.000000001);"
Notice: printf(): Requested precision of 4000000 digits was truncated to PHP maximum of 53 digits in Command line code on line 1
Call Stack:
0.0001 319080 1. {main}() Command line code:0
0.0001 319200 2. printf() Command line code:1
0.00000000100000000000000006228159145777985641889706869
As this example shows, there is not only a common value (6 digits) but also a maximum (probably depended on the computer system PHP executes on), here truncated to 53 digits in my case as the warning shows.
Because of your question I'd say you want to display:
0.000000001
Which are nine digits, so you need to write it that way:
sprintf('%.9F',$ret)
However, you might want to do this:
rtrim(sprintf('%.20F', $ret), '0');
which will remove zeroes from the right afterwards:
0.000000001
Hope this is helpful.
You need to add precision specifier (how many decimal digits should be displayed for floating-point numbers). Something like this:
echo sprintf('%.10f',$ret); // 0.0000000010
If you have no idea what number you should specify, just give it a big number and combine it with rtrim()
.
echo rtrim(sprintf('%.20f', $ret), '0'); // 0.000000001
The code above will strip any 0
's from the end of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With