如果 Javascript 中超过 8 位小数,如何将数字向下舍入到 8 位小数
How to round a number down to 8 decimal places if its over 8 decimal places in Javascript
我正在尝试检查输入的数字是否超过 8 位小数,如果是,那么我想将其四舍五入到小数点后 8 位。但是,当我输入数字 1.234001 时,它会自动将其四舍五入到小数点后 8 位。 (1.234001 / 0.00000001) % 1 = 0 所以我不确定为什么要四舍五入。
这是我的代码
var SAT = 0.00000001;
if(!isNaN(input.value) && ((input.value / SAT) % 1 != 0)) {
input.value = parseFloat(input.value).toFixed(8);
console.log(6);
}
这样试试:
function nrOfDecimals(number) {
var match = (''+number).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
var decimals = Math.max(0,
(match[1] ? match[1].length : 0)
// Correct the notation.
- (match[2] ? +match[2] : 0));
if(decimals > 8){
//if decimal are more then 8
number = parseFloat(number).toFixed(8);
}
//else no adjustment is needed
return number;
}
我正在尝试检查输入的数字是否超过 8 位小数,如果是,那么我想将其四舍五入到小数点后 8 位。但是,当我输入数字 1.234001 时,它会自动将其四舍五入到小数点后 8 位。 (1.234001 / 0.00000001) % 1 = 0 所以我不确定为什么要四舍五入。 这是我的代码
var SAT = 0.00000001;
if(!isNaN(input.value) && ((input.value / SAT) % 1 != 0)) {
input.value = parseFloat(input.value).toFixed(8);
console.log(6);
}
这样试试:
function nrOfDecimals(number) {
var match = (''+number).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
var decimals = Math.max(0,
(match[1] ? match[1].length : 0)
// Correct the notation.
- (match[2] ? +match[2] : 0));
if(decimals > 8){
//if decimal are more then 8
number = parseFloat(number).toFixed(8);
}
//else no adjustment is needed
return number;
}