js-20170616-Number对象

1.Number 对象实例的方法
1.1 Number.prototype.toString()
Number对象部署了自己的toString方法,用来将一个数值转为字符串形式。
(10).toString() // "10"
toString方法可以接受一个参数,表示输出的进制。如果省略这个参数,默认将数值先转为十进制,再输出字符串;否则,就根据参数指定的进制,将一个数字转化成某个进制的字符串。
(10).toString(2) // "1010"
(10).toString(8) // "12"
(10).toString(16) // "a"
1.2 Number.prototype.toFixed()
toFixed方法用于将一个数转为指定位数的小数,返回这个小数对应的字符串。
toFixed方法的参数为指定的小数位数,有效范围为0到20
(10.95).toFixed(1) // "10.9"
(10.96).toFixed(1) // "11.0"
1.3 Number.prototype.toExponential()
toExponential方法用于将一个数转为科学计数法形式。
(10).toExponential() // "1e+1"
(10).toExponential(1) // "1.0e+1"
(10).toExponential(2) // "1.00e+1"
1.4 Number.prototype.toPrecision()
toPrecision方法用于将一个数转为指定位数的有效数字。
(12.34).toPrecision(1) // "1e+1"
(12.34).toPrecision(2) // "12"
(12.34).toPrecision(3) // "12.3"
(12.34).toPrecision(4) // "12.34"
(12.34).toPrecision(5) // "12.340"
toPrecision方法的参数为有效数字的位数,范围是1到21,超出这个范围会抛出RangeError错误。
toPrecision方法用于四舍五入时不太可靠,跟浮点数不是精确储存有关。
1.5 自定义方法
与其他对象一样,Number.prototype对象上面可以自定义方法,被Number的实例继承。
Number.prototype.add = function (x) {
return this + x;
};
上面代码为Number对象实例定义了一个add方法。
在数值上调用某个方法,数值会自动转为Number的实例对象,所以就得到了下面的结果。
8['add'](2) // 10或
(8).add(2) // 10
 
 
 
 
 
原文地址:https://www.cnblogs.com/jialuchun/p/7283563.html