Leanote's Blog
I love Leanote!
Toggle navigation
Leanote's Blog
Home
Chrome
Git
Linux
Windows
Others
工具大全
VsCode
Expo
Html
JavaScript
Npm
Node
Mock
React-Native
React
TypeScript
小程序
插件
正则
Dva
Ant-Design-React
Umi
Vue
Vux
Ant-Design-Vue
Http
Java
flutter
开发小工具
About Me
Archives
Tags
javaScript toFixed()四舍五入失真
2021-05-21 10:16:17
18
0
0
admin
``` Number.prototype.toFixed = function (n) { if (n != undefined && (isNaN(n) || Number(n) > 17 || Number(n) < 0)) { throw new Error("输入正确的精度范围") } // 拆分小数点整数和小数 var num = this var f = "" if (Number(num) < 0) { num = -Number(num) f = "-" } var numList = num.toString().split(".") // 整数 var iN = numList[0] // 小数 var dN = numList[1] n = parseInt(n) if (isNaN(n) || Number(n) === 0) { // 0或者不填的时候,按0来处理 if (dN === undefined) { return f + num + "" } var idN = Number(dN.toString().substr(0, 1)) if (idN >= 5) { if (Number(iN) < 0) { iN = Number(iN) - 1 } else { iN = Number(iN) + 1 } } return f + iN + "" } else { var dNL = dN === undefined ? 0 : dN.length if (dNL < n) { // 如果小数位不够的话,那就补全 var oldN = num.toString().indexOf(".") > -1 ? num : num + "." var a = Number(n) - dNL while (a > 0) { oldN += "0" a-- } return f + oldN } // 正常 var olddN = dN.toString().substring(0, n) var dN1 = Number(dN.toString().substring(0, n)) var dN2 = Number(dN.toString().substring(n, n + 1)) if (dN2 >= 5) { dN1 += 1 if (olddN.length - dN1.toString().length > 0) { var olddNL = olddN.length - dN1.toString().length while (olddNL > 0) { dN1 = "0" + dN1 olddNL-- } } if (dN1.toString().length > n) { if (Number(iN) < 0) { iN = Number(iN) - 1 } else { iN = Number(iN) + 1 } dN1 = "0" while (n > 1) { dN1 += "0" n-- } } } else { dN1 = olddN } return f + iN + "." + dN1 } } ```
Pre:
vue初始化组件data中的数据
Next:
常用全局样式
0
likes
18
Weibo
Wechat
Tencent Weibo
QQ Zone
RenRen
Submit
Sign in
to leave a comment.
No Leanote account?
Sign up now.
0
comments
More...
Table of content
No Leanote account? Sign up now.