所以 :)
我有一些数字。我想根据 .
符号后的数字对它们进行舍入。问题是我不知道 .
.
我知道函数 toPrecision()
和 toFixed()
但它们必须传递参数。所以我必须知道我需要在小数点后得到多少符号,但我不知道。
我想达到什么目的?
+++++++++++++++++++++++++++++++++++
+ before + after +
+++++++++++++++++++++++++++++++++++
+ 0.0072512423324 + 0.0073 +
+ 0.032523 + 0.033 +
+ 0.000083423342 + 0.000083 +
+ 15.00042323 + 15.00042 +
+ 1.0342345 + 1.034 +
+++++++++++++++++++++++++++++++++++
我怎样才能做到这一点?
最佳答案
尝试使用这个:
function roundAfterZeros(number,places){
var matches=number.toString().match(/\.0*/);
if(!matches)return number.toString();
return number.toFixed(matches[0].length-1+places);
}
这里有解释
var matches = number.toString().match(/\.0*/)
检查点 (.
)。
if(!matches)return number.toFixed(places);
如果没有点(.
),一定是整数,所以我们直接return它(作为一致性的字符串)。
return number.toFixed(matches[0].length-1+places);
如果是小数,我们会将其四舍五入到零后最接近的数字(0
)。
然后像 roundAfterZeros(0.000083423342,2)
一样运行它:
0.000083423342 to "0.000083"
1.0342345 to "1.034"
1 to "1"
0.5 to "0.50"
-300 to "-300"
关于javascript - 四舍五入无理数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23095049/