(PHP) How to avoid scientific notation and show the actual large numbers? [duplicate]
Asked Answered
S

2

10

I have been working with the PHP code that the expected result will become :

1
101
10001
1000001
100000001
10000000001
1000000000001
100000000000001
10000000000000001
1000000000000000001


finally the output was :

1
101
10001
1000001
100000001
10000000001
1000000000001     // (1 billion) to (100 billion - 1) still showing the actual number, and then
1.0E+14
1.0E+16
1.0E+18


I've found some solutions there! they said by using sprintf or trying format_number. I tried both.

using sprintf and the result :

$format_x = sprintf("%.0f ",$x);
echo $format_x.$br;

1
101
10001
1000001
100000001
10000000001
1000000000001
100000000000001
10000000000000000
1000000000000000000


using format_number and the result :

echo number_format($x, 0).$br;

1
101
10,001
1,000,001
100,000,001
10,000,000,001
1,000,000,000,001
100,000,000,000,001
10,000,000,000,000,000
1,000,000,000,000,000,000


but it still doesn't show the actual large numbers. well, the two ways was looks good but it doesn't fit with what i want. does anyone can resolve this?

Syncopate answered 20/8, 2013 at 6:26 Comment(0)
L
9

You can use standard bc_math library to handle operations with large numbers. Please, note, that in this case your numbers will be represented as strings, but library provides specific methods for operations under such strings.

Leacock answered 20/8, 2013 at 6:30 Comment(2)
For integers - may be. But topic starter mentioned 'large numbers' - i.e. could be floats.Leacock
i just knew the bc_math function. can you help me how the bc_math works on the code above? i've tried bcpow but doesn't work. is must include the bcpow's function first on my php file?Syncopate
P
3

You should definitely use BCMath.

If you want to know why you can't do it with regular numbers, it's because they are floating point numbers and they are using a fixed amount of space in the memory(64 bits to be exact) so their precision is physically limited. Otherwise a string is not limited because that would be stupid if the length of a text was limited. That's why BcMath and other libraries uses string for arithmetical computation.

If you want to learn more about the format used by PHP(and almost every language) to store big numbers you can go there : http://en.wikipedia.org/wiki/Double-precision_floating-point_format

Have a good day

Pender answered 20/8, 2013 at 6:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.