Number In Javascript #
The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value.
is for double-precision 64-bit and for single-precision 32-bit.
Number.parseFloat() #
This method has the same functionality as the global parseFloat() function:
// eslint-disable-next-line unicorn/prefer-number-properties
parseFloat === Number.parseFloat // trueparseFloat() use DFA to parse string to number, when it meets a abnormal character, it will stop and return the number parsed so far, parseInt() is similar.
For example:
Number.parseFloat('123.456abc') // 123.456
Number.parseFloat('12.3.41bc') // 12.3
Number.parseFloat('-0x123') // -0
Number.parseFloat('.11.1') // 0.11
Number.parseFloat('..1') // NaN
Number.parseFloat('+1.1e-2') // 0.011
Number.parseFloat('a1.1e-2') // NaN
Number.parseFloat('.1e-2.5') // 0.001Why 0.1 + 0.2 !== 0.3 #
in IEEE754 is below:
in IEEE754 is below:
Here is the process of add-operation for double-precision 64-bit binary format IEEE 754:
- Align the exponents, the smaller one will be shifted right until the exponents are equal.
- Add the mantissas.
- Normalize the result (and judge if it is overflow or underflow).
- Round the result to the nearest representable value.
Now we can get the binary sum result of and : . .
.
. sign = 0 exponent = -2 + 1023 => 01111111101 mantissa = 0011001100110011001100110011001100110011001100110011100 =>0011001100110011001100110011001100110011001100110100
So the sum of and in IEEE754 is below:
which is equal to .
Why 0.2 - 0.1 === 0.1 #
. .
.
. sign = 0 exponent = -4 + 1023 => 01111111011 mantissa = 1001100110011001100110011001100110011001100110011010 =>1001100110011001100110011001100110011001100110011010
So the subtraction of and in IEEE754 is below:
which is equal to .