JS原始类型:数值的运用技巧

保留特定位数的小数

有一些题目常常要求格式化数值,:比如保存几位小数等等。
1.使用Number.prototype.toFixed() 原生方法。该方法的参数为要保存的小数位数,有效范围为0到20,超出这个范围将抛出RangeError错误。此方法以四舍五入的方式处理多出的小数。
语法为:

numObj.toFixed([digits])

例子:

var temp = 3.141592653;
console.log(temp.toFixed(2));
//输出为3.14
//此方法以四舍五入的方式处理多出的小数。
console.log(temp.toFixed(4));
//输出为3.1416

如需要将末尾多余的0舍去,可以这样写:

var temp1 = 3.0596;
console.log(temp1.toFixed(3)*1000/1000);
//输出为3.06

2.使用Math.round() 方法。

var temp2 = 2.17698;
console.log(Math.round(temp2*1000)/1000);
//输出为2.177
//试一试能不能去掉末尾多余的0
var temp2 = 2.17998;
console.log(Math.round(temp2*1000)/1000);
//输出为2.18,可以去掉末尾多余的0

Math.ceil()也适用于这种写法。

3.使用字符串对象的substr方法。

var temp3 = 1.0836;
var res = String(temp3).substr(0,String(temp3).indexOf('.')+3)
console.log(Number(res))
//输出为1.08

进制相互转换

其他进制转为十进制使用parseInt()方法:
Number.parseInt() 方法可以根据给定的进制数把一个字符串解析成整数,语法为:

Number.parseInt(string[, radix])

例子:

var res = Number.parseInt('123',16);
console.log(res);
//输出为291,也即十六进制的123转为十进制为291
var res = Number.parseInt('123',8);
console.log(res);
//输出为83

**注意:**parseFloat()并无这样的特性,该方法只是纯粹的转化浮点数的功能

十进制转为其他进制:Number对象部署了单独toString()方法,可以接受一个参数,表示将一个数字转化为某个进制的字符串。

(10).toString() //输出为‘10’
(10).toString(2)//输出为‘1010’
(10).toString(8)//输出为‘12’
(10).toString(16)//输出为‘a’

注意该方法改变了数据类型

console.log(typeof (10).toString(2))//输出为string
posted @ 2016-06-02 20:19  西河  阅读(192)  评论(0编辑  收藏  举报