JS中的toFixed,toExponential,toPrecision

toFixed():根据小数点后的指定位数,将数字转换为字符串,它不用指数计数法。blog

toExponential():根据小数点后指定位数,将数字转化为指数形式字符串。小数点前面只有一位,小数点后面的位数,有参数指定。ci

toPrecision():根据有效数字位数,将数字转化为字符串。若是有效数字位数少于数字整数部分,则表示成指数形式字符串。字符串

以上三个方法,都遵循“四舍五入”或者补0的原则。io

下面是一些例子:console

var num = 1234567.8999;
console.log("num.toFixed(0):" + num.toFixed(0));
console.log("num.toFixed(2)" + num.toFixed(2));
console.log("num.toFixed(5)" + num.toFixed(5));
console.log("num.toFixed(12)" + num.toFixed(12));

console.log("num.toExponential(3):" + num.toExponential(3));
console.log("num.toExponential(0):" + num.toExponential(0));

console.log("num.toPrecision(1):" + num.toPrecision(1));
console.log("num.toPrecision(5)" + num.toPrecision(5));
console.log("num.toPrecision(12)" + num.toPrecision(12));

对应下面的输出:方法

相关文章
相关标签/搜索