分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 教程案例

黄聪:JS数学计算精度修正

发布时间:2023-09-06 02:07责任编辑:蔡小小关键词:暂无标签

问题描述

如果我问你,4330.61乘以100等于多少,我猜你肯定跟我说:“肯定是 433061”啊!
是啊,要我我也是这么回答,来来来我们来看看浏览器怎么说吧,如下图

 
浏览器告诉我,他就是算不对

偌!浏览器告诉我,他就是算不对,这要是给客户算钱,客户不就有意见了....
WHY?计算机计算出来的还不如我自己的心算呢!!!!
如果你想了解什么原因,您请看=>js浮点数精度问题的前世今生?

解决办法

;(function(){ ?function mathService(){ ???this.add=function(a,b){ ?????var c, d, e; ?????try { ???????c = a.toString().split(".")[1].length; ?????} catch (f) { ???????c = 0; ?????} ?????try { ???????d = b.toString().split(".")[1].length; ?????} catch (f) { ???????d = 0; ?????} ?????return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) + this.mul(b, e)) / e; ??} ??this.mul=function(a, b) { ?????var c = 0, ???????d = a.toString(), ???????e = b.toString(); ?????try { ???????c += d.split(".")[1].length; ?????} catch (f) {} ?????try { ???????c += e.split(".")[1].length; ?????} catch (f) {} ?????return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c); ???} ??this.sub=function(a,b){ ????var c, d, e; ????try { ??????c = a.toString().split(".")[1].length; ????} catch (f) { ??????c = 0; ????} ????try { ??????d = b.toString().split(".")[1].length; ????} catch (f) { ??????d = 0; ????} ????return e = Math.pow(10, Math.max(c, d)), (this.mul(a, e) - this.mul(b, e)) / e; ??} ??this.div=function(a, b) { ????var c, d, e = 0, ??????f = 0; ????try { ??????e = a.toString().split(".")[1].length; ????} catch (g) {} ????try { ??????f = b.toString().split(".")[1].length; ????} catch (g) {} ????return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), this.mul(c / d, Math.pow(10, f - e)); ??} ?} ?window.mathService=new mathService()})(window);

来来来,用起来

 
image.png

Ok!写完收工!!!



作者:小枫学幽默
链接:https://www.jianshu.com/p/c3374517b976
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

黄聪:JS数学计算精度修正

原文地址:https://www.cnblogs.com/huangcong/p/9402452.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved