首页 > 其他 > 详细

运算精度问题

时间:2018-09-10 14:22:25      阅读:196      评论:0      收藏:0      [点我收藏+]
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));
},
};

运算精度问题

原文:https://www.cnblogs.com/adanxiaobo/p/9619200.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!