栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在JavaScript中舍入到小数点后1位?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在JavaScript中舍入到小数点后1位?

Math.round(num * 10) / 10
可行,这是一个例子…

var number = 12.3456789var rounded = Math.round(number * 10) / 10// rounded is 12.3

如果您希望它保留一位小数,即使该位是0,也可以添加…

var fixed = rounded.toFixed(1)// fixed is always to 1 d.p.// NOTE: .toFixed() returns a string!// To convert back to number formatparseFloat(number.toFixed(2))// 12.34// but that will not retain any trailing zeros// So, just make sure it is the last step before output,// and use a number format during calculations!

编辑:添加具有精度功能的回合…

使用这个原理作为参考,这里有一个方便的小舍入函数,它需要精确…

function round(value, precision) {    var multiplier = Math.pow(10, precision || 0);    return Math.round(value * multiplier) / multiplier;}

…用法…

round(12345.6789, 2) // 12345.68round(12345.6789, 1) // 12345.7

…默认舍入到最接近的整数(精度0)…

round(12345.6789) // 12346

…并可以四舍五入到最接近的10或100等…

round(12345.6789, -1) // 12350round(12345.6789, -2) // 12300

…以及正确处理负数…

round(-123.45, 1) // -123.4round(123.45, 1) // 123.5

…并且可以与toFixed组合以一致地格式化为字符串…

round(456.7, 2).toFixed(2) // "456.70"


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614664.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号