我如何在js中像Excel中的圆形函数一样以负的精度舍入一个数字
我正在尝试从8904000到8900000的值。有没有什么可能的方法来改变这个使用Math.round。 在MS Excel中的例子
=round(8904000,-5); ANS: 8900000
我尝试了下面的代码,但Math.round不采取第二个参数
Math.round(8904000,-5); ANS: 8904000
总之我想把这个数字凑到最接近的100,000个数字
所以5300 * 56 * 30 = 8904000变成8900000
尝试这个,
function roundDown(number, decimals) { decimals = decimals || 0; return ( Math.floor( number * Math.pow(10, decimals) ) / Math.pow(10, decimals) ); } roundDown(8904000, -5)
四舍五入到小数点的常见解决scheme是:
- 使用
Number.prototype.toFixed()
- 乘以
power of 10
的一些power of 10
的float
,以利用Math.round()
。
这两个工作,除了有时一个小数5被舍去,而不是up.rounding问题可以避免使用数字表示在指数表示法
尝试这个
function round(value, decimals) { return Number(Math.round(value+'e'+decimals)+'e-'+decimals); } round(8904000, 5)
Math.round(value/1000000)*1000000
将value
除以舍入unit
,即1000000
, Math.round()
数字并multiply
指定的unit
。