JavaScript保留指定有效小数位数
2021-09-23 本文已影响0人
Hi___World
需求:保留指定位数的小数位数
例如:
// 保留两位
1.0012589 => 期待值:1.0013
1.0012489 => 期待值:1.0012
1.00999 => 期待值:1.01
1.11011 => 期待值:1.11
1.0 => 期待值:1
-1.0 => 期待值:-1
0.0109 => 期待值:0.011
123.999 => 期待值:124
// 保留三位
1.0012589 => 期待值:1.00126
1.0012489 => 期待值:1.00125
1.11011 => 期待值:1.11
1.0 => 期待值:1
-1.0 => 期待值:-1
0.0109 => 期待值:0.0109
123.999 => 期待值:124.999
废话少说直接上代码:
/**
*
* @param {*} num 要处理的小数
* @param {*} digit 要保留的位数
* @returns 指定有效位数小数
*/
let getRes = (num, digit = 3) => {
if (Number(num) === Math.floor(num)) return Math.floor(num);
let res = [], addNum = 0;
num += '';
let [zs, xs] = num.split('.');
let [, symbol, zsNum] = /^(\-?)(\d+\.\d+|\d+)$/.exec(zs);
for (let i = 0; i < xs.length; i++) {
const ele = xs[i];
if (ele != 0) {
if (xs[i + digit] && xs[i + digit] > 4) {
addNum = 1;
for (let j = i + (digit - 1); j >= 0; j--) {
if (Number(xs[j]) + addNum == 10) res[j] = '0';
else {
res[j] = Number(xs[j]) + addNum;
addNum = 0;
}
}
}
else {
for (let k = i; k <= i + (digit - 1); k++) {
res[k] = xs[k];
}
}
break;
} else res[i] = xs[i];
}
return Number(symbol + (Number(zsNum) + addNum) + '.' + res.join(''));
}