运算精度问题
Posted adanxiaobo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了运算精度问题相关的知识,希望对你有一定的参考价值。
export default {
add(num1, num2) {
let r1;
let r2;
try { r1 = num1.toString().split(‘.‘)[1].length; } catch (e) { r1 = 0; }
try { r2 = num2.toString().split(‘.‘)[1].length; } catch (e) { r2 = 0; }
const m = 10 ** Math.max(r1, r2);
const n = (r1 >= r2) ? r1 : r2;
return ((num1 * m + num2 * m) / m).toFixed(n);
},
sub(num1, num2) {
let r1;
let r2;
try { r1 = num1.toString().split(‘.‘)[1].length; } catch (e) { r1 = 0; }
try { r2 = num2.toString().split(‘.‘)[1].length; } catch (e) { r2 = 0; }
const n = (r1 >= r2) ? r1 : r2;
const m = 10 ** Math.max(r1, r2);
return ((num1 * m - num2 * m) / m).toFixed(n);
},
mul(num1, num2) {
let m = 0;
try { m += num1.toString().split(‘.‘)[1].length; } catch (e) { m += 0; }
try { m += num2.toString().split(‘.‘)[1].length; } catch (e) { m += 0; }
return (Number(num1.toString().replace(‘.‘, ‘‘)) * Number(num2.toString().replace(‘.‘, ‘‘))) / (10 ** m);
},
div(arg1, arg2) {
let t1;
let t2;
try { t1 = arg1.toString().split(‘.‘)[1].length; } catch (e) { t1 = 0; }
try { t2 = arg2.toString().split(‘.‘)[1].length; } catch (e) { t2 = 0; }
const r1 = Number(arg1.toString().replace(‘.‘, ‘‘));
const r2 = Number(arg2.toString().replace(‘.‘, ‘‘));
return (r1 / r2) * (10 ** (t2 - t1));
},
};
以上是关于运算精度问题的主要内容,如果未能解决你的问题,请参考以下文章