开发学院

您的位置:首页>教程>正文

教程正文

ES6 toFixed()

ES6 toFixed()

  toFixed()把传递的参数四舍五入为指定小数位数的数字

语法

number.toFixed( [digits] )

参数细节

  digits:规定小数的位数,是 0 ~ 20 之间的值,包括 0 和 20,有些实现可以支持更大的数值范围。如果省略了该参数,将用 0 代替。

返回值

  返回 NumberObject 的字符串表示,不采用指数计数法,小数点后有固定的 num 位数字。如果必要,该数字会被舍入,也可以用 0 补足,以便它达到指定的长度。如果 num 大于 le+21,则该方法只调用 NumberObject.toString(),返回采用指数计数法表示的字符串。

例子

var num3 = 177.234 
console.log("num3.toFixed() is "+num3.toFixed()) 
console.log("num3.toFixed(2) is "+num3.toFixed(2)) 
console.log("num3.toFixed(6) is "+num3.toFixed(6))

输出

num3.toFixed() is 177 
num3.toFixed(2) is 177.23 
num3.toFixed(6) is 177.234000