-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
javascript 实现精度运算 #8
Labels
Comments
sunhengzhe
assigned sunhengzhe, zjlzlr, Joazer, leermao, keer3, Shie0906, miSunLaughing, yusidi, yinkaihui and LYNNEZHAO
Aug 9, 2017
这个问题是在一个前端群里讨论的,放在 这里。后续可以去那里讨论 |
感觉写得不好 function add() {
const result = [...arguments].reduce((x, y) => {
y = y.toString();
// 兼容整数
y = y.indexOf('.') == -1 ? y = y + '.0' : y;
let [intX, floatX] = x.split('.');
let [intY, floatY] = y.split('.');
let floatRet = addStr(floatX, floatY);
floatRet = floatRet.indexOf('.') != -1 ? floatRet.split('.') : (floatRet + '.0').split('.') ;
let intRet = parseInt(intX) + parseInt(intY) + parseInt(floatRet[0]);
return intRet + '.' + floatRet[1];
}, '0.0');
return result;
}
const addStr = (x, y) => {
const xLength = x.length,
yLength = y.length,
maxLength = Math.max(xLength, yLength);
// 填充长度
x = x + Array(maxLength - xLength).fill(0).join('');
y = y + Array(maxLength - yLength).fill(0).join('');
let result = [],
j = 0,
flag = 0;
for(let i = maxLength - 1; i >= 0; i--) {
let r = 0;
r = parseInt(x[i]) + parseInt(y[i]) + flag;
flag = Math.floor(r / 10);
r = r < 10 ? r : r % 10;
result[j++] = r;
}
flag ? result.push(flag) : '';
let ret = '';
if (result.length - maxLength === 0) {
result.reverse().splice(result.length - maxLength, 0, '0.');
} else {
result.reverse().splice(result.length - maxLength, 0, '.');
}
return result.join('');
} |
sunhengzhe
unassigned zjlzlr, sunhengzhe, Joazer, leermao, keer3, Shie0906, miSunLaughing, yusidi, yinkaihui and LYNNEZHAO
Aug 12, 2017
这里可以使用 es6 的 |
if (result.length - maxLength === 0) {
result.reverse().splice(result.length - maxLength, 0, '0.');
} else {
result.reverse().splice(result.length - maxLength, 0, '.');
} 这里的判断实际上就是有无进位,我感觉这个方法返回 function add(/* number1, number2, number3, ... */) {
const result = [...arguments].reduce((x, y) => {
// ...
const { isCarry, decimals } = addStr(floatX, floatY);
const intRet = parseInt(intX) + parseInt(intY) + isCarry; // 自动转型
return intRet + '.' + decimals;
}, '0.0');
return result;
}
const addStr = (x, y) => {
//...
flag ? result.push(flag) : '';
const isCarry = result.length !== maxLength;
if (isCarry) {
result.pop();
}
return {
isCarry,
decimals: result.reverse().join('')
};
} |
还有两个精度有关的补充:
x = 0.2;
y = 0.3;
z = 0.1;
equal = (Math.abs(x - y + z) < Number.EPSILON);
因为 |
EMM 我又碰到了 不过是四舍五入 |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
用 js 实现高精度运算,这个问题是老生常谈了。如果真的要前端做一个高精度运算(比如钱),还是要注意这个问题的。
更一般地,实现四则运算的精度运算
The text was updated successfully, but these errors were encountered: