【JavaScript】Number类型格式化字符串方法toFixed()、toExponential()、toPrecision()

toFixed()方法会按照指定的小数位返回数值的字符串表示

var num = 10; 
console.log(num.toFixed(2)); //"10.00" 
// 给 toFixed()方法传入了数值 2,显示2位小数
var num = 10.005; 
console.log(num.toFixed(2)); //"10.01" 
// 如果数值本身包含的小数位比指定的还多,那么接近指定的最大小数位的值就会舍入

toExponential()方法返回以指数表示法(也称 e 表示法)表示的数值的字符串形式。

var num = 10; 
console.log(num.toExponential(1)); //"1.0e+1" 
// 参数指定输出结果中的小数位数

toPrecision()方法可能会返回固定大小(fixed)格式,也可能返回指数(exponential)格式

var num = 99; 
console.log(num.toPrecision(1)); //"1e+2" 一位数无法准确地表示 99,向上舍入为 100
console.log(num.toPrecision(2)); //"99" 两位数表示
console.log(num.toPrecision(3)); //"99.0" 三位数表示

实际上,toPrecision()会根据要处理的数值决定到底是调用 toFixed()还是调用 toExponential()。

发布了10 篇原创文章 · 获赞 1 · 访问量 305

猜你喜欢

转载自blog.csdn.net/AAABingBing/article/details/104146604