- 2020-11-03 22:01:08
typeof 17; //number typeof 98.6; //number typeof -21.3; //number
Most arithmetic operators can be evaluated using integers, real Numbers, or a combination of both.
0.1 * 0.9; //0.19 -99 + 100; //1 21- 12.3; //8.7 2.5 /5; //0.5 21%8; //5
You can also use the number type toString method to see for yourself:
The arguments to the toString method specify its conversion cardinality, which is represented in radix 2 (that is, base 2) in this example. The resulting value omits the extra 0 (bits) at the left end because they do not affect the final value.
The integer 1 is represented as 32-bit base 2 as follows:
Merges two sequences of bits by bit or operation expression. As long as any one bit of the two bits involved in the operation is 1, that bit of the operation result is 1. The results expressed in bit mode are as follows:
This sequence represents the integer 9. You can use the standard library function parseInt to verify, again with base 2:
parseInt("1000", 2); //9
(Again, the leading 0 bits are not necessary because they do not affect the result of the operation.)
The final caveat with floating-point Numbers is that you should always be on your guard against them. Floating point Numbers may seem familiar, but they are notoriously imprecise. Even the simplest arithmetic operations produce incorrect results.
Although 64-bit precision is already quite high, double-precision floating-point Numbers represent only a finite set of Numbers, not all sets of real Numbers. Floating-point arithmetic produces only approximate results, with 4 rounded to the nearest representable real Numbers. As you perform a series 1 operation, the results become less and less accurate as the rounding errors accumulate. Rounding can also cause a number of unexpected deviations from the normally expected laws of arithmetic operations. For example, real Numbers satisfy the associative law, which means that for any real number x, y, z, it always satisfies (x + y) + z = x + (y + z).
However, this is not always the case with floating-point Numbers.
( 0.1+0.2 ) +0.3; //0.60000000000000001 0.1+(0.2+ 0.3); //0.6
Floating point Numbers weigh precision against performance. When we are concerned about precision, we should be careful about the limitations of floating point Numbers. An effective solution is to use integer values as much as possible, since integers do not need to be rounded in their representation. When doing a currency correlation calculation, programmers usually convert the value proportionately to the smallest monetary unit for representation before doing the calculation, so that the calculation can be done as an integer. For example, if the above calculation is in dollars, then we can convert it to an integer representing cents for the calculation.
(10+20)+30; //60 10+ (20+30); //60
For integer operations, you don't have to worry about rounding errors, but you should be careful that all calculations only apply to integers with a value of 253 ~ 253.