javascript - 为什么将 Math.round 输入乘以 1000 然后除以结果?
问题描述
从温度转换的函数写在下面
function tryConvert(temperature, convert /*callback*/) {
const input = parseFloat(temperature);
if (Number.isNaN(input)) {
return '';
}
const output = convert(input);
const rounded = Math.round(output * 1000) / 1000;
return rounded.toString();
}
我的问题是这一行:
const rounded = Math.round(output * 1000) / 1000;
为什么需要乘以 1000?并将结果除以 1000?
解决方案
乘以 1000 将小数点向右移动 3 位。5.333333 = > 5333.333
四舍五入到整数。(小数点后只有零)5333.333 = > 5333.000
之后除以 1000 将小数点移回它的开始位置。5333.000 = > 5.333000
结果是,该数字被四舍五入到小数点后 3 位。5.333333 = > 5.333000
推荐阅读
- konvajs - 如何在 KonvaJS 中输入数学?(集成 MathQuill 或类似软件)
- sql - 为什么 Azure SQL 数据库如此昂贵?
- android - gradlew 可以运行我的浓缩咖啡测试,而不仅仅是“单元”测试吗?
- react-native - 为具有许多声音文件的 ios 构建时的博览会问题
- bayesian - 如何在pyMC3中实现多个随机变量的可能性加权乘积?
- r - 如何使用 simpleboot 包获得线性模型系数的 CI 95%
- java - 用junit写一个测试用例
- python - 如何修复“int”对象不可下标”
- xml - 如何使用 XSL 处理单独的 XML 元素
- python - 名称生成器问题:如何修改代码为我指定的每个标准提供多个(例如 20 个)名称选项