Viewed   76 times

I have a floating point number in exponential format i.e. 4.1595246940817E-17 and I want to convert it into decimal number like 2.99 etc.

Any help will be appreciated.

format_number() sprintf() don't seem to be working for me.

 Answers

5

You need a better math extension like BC Math, GMP... to handle the more precise precision.

Limitation of floating number & integer

Wednesday, October 19, 2022
5

Add floor() around your number_format:

$sku = '2200081005966';
echo floor(number_format(substr($sku, 7, 12), 0, '', '.')*100)/100;

Outputs:

5.96

Note: It would works well in case of positive numbers, your substr always take a positive number, that's why it would be enough.

Tuesday, September 6, 2022
 
akb
 
akb
3

You aren't doing anything wrong. Floats are notoriously innaccurate. From the docs (In the huge red warning box):

Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

Friday, October 14, 2022
 
tami
 
3

Neither. If it were an implementation of floating point it would be subject to the same inaccuracies as FLOAT and REAL types. See Floating Point on wikipedia.

MONEY is a fixed point type.

It's one byte smaller than a DECIMAL(19,4), because it has a smaller range (922,337,203,685,477.5808 to 922,337,203,685,477.5807) as opposed to (-10^15+1 to 10^15-1).

Wednesday, December 7, 2022
 
4

Provide correct output for this so that we test and throw few more sample data.

Try this,

SELECT CONVERT(decimal(18,8), CAST('5E-05' AS FLOAT))
Sunday, November 20, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :