Number 类型

Javascript使用IEEE -754格式存储整型和浮点型(有些语言称为双精度)
因为这种存储格式,所以javascript中有正的0和负的0
 
整型也可以存储八进制和十六制
 
八进制第一个数为0,后面跟着的数如果大于八,会自动转化为十进制
078  将会被解释为78
在strict mode里面八进制是不合法的,会出现异常
 
16进制以0x开头
在算法里面八进制和十六进制都会被当作十进制处理
 
浮点型(小数)的存储内存是整型的两倍,所以javascript总是试图把浮点型转为整型
1.0会被转为整型1, 1.忘记加后面的数字也会被转为1
 
要表示很大的类型可以使用e(E)符号,表示10的次方
3.125e7    表示31250000
 
可以表示很小的数 3e-7代表0.00000003,javascript会自动把小数点后有六个或以上0的小数都转化为e格式
 
Floating-point values are accurate up to 17 decimal places but are far less accurate in arithmetic computations than whole numbers.
例如0.1+0.2=0.30000000000000004
0.05+0.25=0.3
0.15+0.15=0.3这样又是正常的
这并不是ecmascript才有的错误,只要采用IEEE-754存储都会有这样问题
 
因为内存限制,数字大小是有范围的
最小的Number.MIN_VALUE and is 5e-324 on most browsers
最大的Number.MAX_VALUE and is 1.7976931348623157e+308 on most browsers
如果超出了这个范围小的转化为-infinity,大于最大值的为infinity
 
在其他语言中除以0会抛出异常,在ecmascript会得到NaN,这样程序会继续运行下去
用isNAN()判断时会尝试把传进去的参数转化为数字判断
alert(isNaN(“blue”));   输出true
alert(isNaN(true));输出false
 
有三个函数可以把非数字内容转化为数字
Number()
- ➤  When applied to Boolean values, true and false get converted into 1 and 0, respectively.
- ➤  When applied to numbers, the value is simply passed through and returned.
 
- ➤  When applied to null, Number() returns 0.
 
- ➤  When applied to undefined, Number() returns NaN.
 
- ➤  When applied to strings, the following rules are applied:
 
    - ➤  If the string contains only numbers, optionally preceded by a plus or minus sign, it is always converted to a decimal number, so “1” becomes 1, “123” becomes 123, and “011” becomes 11 (note: leading zeros are ignored).
 
    - ➤  If the string contains a valid floating-point format, such as “1.1”, it is converted into the appropriate floating-point numeric value (once again, leading zeros are ignored).
 
    - ➤  If the string contains a valid hexadecimal format, such as “0xf”, it is converted into an integer that matches the hexadecimal value.
 
    - ➤  If the string is empty (contains no characters), it is converted to 0.
 
    - ➤  If the string contains anything other than these previous formats, it is converted into NaN.
 
- ➤  When applied to objects, the valueOf() method is called and the returned value is converted based on the previously described rules. If that conversion results in NaN, the toString() method is called and the rules for converting strings are applied.
 
parseInt()从第一个字符开始转化,忽略开头的空格,直到遇到非数字或到结尾停止,如果符合十六进制语法的会转化为十六进制
 
var num1 = parseInt(“1234blue”);  结果为1234
var num2 = parseInt(“”);     结果为NaN,和Number()不同
var num3 = parseInt(“0xA”);   十六进制 10
var num4 = parseInt(22.5);    22
var num5 = parseInt(“70”);     70
 
在ECMAScript 3 and 5该函数有区别
var num = parseInt(“070”);       //56 (octal) in ECMAScript 3, 0 (decimal) in ECMAScript 5
在第五版中,解析八进制的能力从引擎移除了,所以0开头被认为是无效的,返回0
因此使用时最好添加radix
var num1 = parseInt(”AF”, 16); //175
var num2 = parseInt(”AF”); //NaN
 
parseFloat()是没有基数可以添加的,因此0开头的话都会转化为0,如果是E的字符,能够转化为整型
 
parseFloat(“3.125e7”);      转化为31250000
原文地址:https://www.cnblogs.com/chuangweili/p/5163783.html