Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display float value w/o scientific notation

Tags:

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?

like image 766
Johni Avatar asked Jun 06 '12 14:06

Johni


2 Answers

sprintf('%f',$ret) doesn't work, it returns 0.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.

like image 138
hakre Avatar answered Sep 21 '22 02:09

hakre


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.

like image 35
flowfree Avatar answered Sep 19 '22 02:09

flowfree