我想计算一些创建值0.0034657、0.000002376876868、0.00004557600等的百分比,就像我的反应项目中的这个bt一样,我想对上述值进行四舍五入并像这样打印这些值0.0034、0.0000023、0.000045。请有人告诉我这个的逻辑或任何算术函数。
值:0.0034657、0.000002376876868、0.00002357600 预期输出:0.0034、0.0000023、0.000023
这是一个通用的解决方案,您可以传入任何数字作为第二个参数
尚未使用负值进行测试 - 如果需要,请自行处理
已为您添加:p
const special = (v, n = 2) => {
const s = Math.sign(v);
if (!s) {
return 0;
}
const digits = 10 ** ((n - 1) - Math.floor(Math.log10(s * v)));
return s * Math.floor(s * v * digits)/digits;
}
console.log([0, 0.0034657, 0.000002376876868, 0.00002357600, -0.00002357600].map(v => special(v)));
我认为你可以使用
toFixed
方法
像这样:
const roundToDecimal = (value, decimalPlaces) => {
const rounded = Number(value).toFixed(decimalPlaces);
return Number(rounded)
}
const values = [0.0034657, 0.000002376876868, 0.00002357600];
const roundedValues = values.map(value => roundToDecimal(value, 4))
console.log(roundedValues);
const roundToDecimal = (value, decimalPlaces) => {
const rounded = Number(value).toFixed(decimalPlaces);
return Number(rounded)
}
const values = [0.0034657, 0.000002376876868, 0.00002357600];
const roundedValues = values.map(value => roundToDecimal(value, 4))
console.log(roundedValues);