javascript - 将数字四舍五入到 1
问题描述
我要做的是将数字向左舍入到 1。例如,如果一个数字是 12345.6789,则向下舍入到 100000.0000 ..如果数字是 9999999.9999,则向下舍入到 1000000.0000。还希望它适用于小数,所以如果一个数字是 0.00456789,则将其四舍五入为 0.00100000。
在这个例子中,5600/100000 = 0.056,我希望它四舍五入到 0.01。我在 LUA 脚本中使用以下代码,它运行良好。
function rounding(num)
return 10 ^ math.floor((math.log(num))/(math.log(10)))
end
print(rounding(5600/100000))
但是如果我对 Javascript 使用相同的值,它会返回 -11,而不是 0.01。
function rounding(num) {
return 10 ^ Math.round((Math.log(num))/(Math.log(10)))
}
console.log((rounding(5600/100000)).toFixed(8))
任何帮助或指导将不胜感激。
解决方案
您可以将 log 10值设为底,并以 10 为底数取回指数值的值。
不能保存带零的小数位。
const format = number => 10 ** Math.floor(Math.log10(number));
var array = [
12345.6789, // 100000.0000 this value as a zero to much ...
9999999.9999, // 1000000.0000
0.00456789, // 0.00100000
];
console.log(array.map(format));
推荐阅读
- javascript - WebRTC 有多少个通道以及使用了哪些传输?
- c# - 需要帮助提高 SQL DELETE 性能
- windows - 当您作为修饰键时,我的功能/Fn 键不起作用
- java - 如何在不知道 DPI 的情况下获得以英寸为单位的图像尺寸?
- javascript - 尝试使用间隔更改 React Hooks 中的状态
- javascript - Paypal 付费墙自定义文本 css
- python - 不处理词云停用词
- sql - Redshift 跳过 split_part() 的第一个字符
- javascript - Formik 的表单无法识别 Material UI 组件的文本字段值?
- r - 以编程方式循环列表