精度丢失
相信很多小伙伴都知道在JavaScript中,有精度丢失这个问题,本篇文章将结合各位大神的思想以及融入自己的思想实现解决此问题方法
话不多说,直接上代码:
/**
* 计算方法 calc
* @param { number } type :0 加 1 减 2 乘 3 除
* @param { String | Number } a :计算数a
* @param { String | Number } b :计算数b
* @param { Number } digit :结果保留的位数
* @return Number | String
*/
function calc
(type
,a
,b
,digit
){
let r1
, r2
;
try
{ r1
= a
.toString
().split(".")[1].length
} catch
(e
) { r1
= 0 }
try
{ r2
= b
.toString
().split(".")[1].length
} catch
(e
) { r2
= 0 }
let maxLen
= Math
.pow(10, Math
.max(r1
, r2
))
let tyeps
= [
(Math
.round(maxLen
*a
) + Math
.round(maxLen
*b
))/maxLen
,//加
(Math
.round(maxLen
*a
) - Math
.round(maxLen
*b
))/maxLen
,//减
(Math
.round(maxLen
*a
) * Math
.round(maxLen
*b
))/(maxLen
*maxLen
),//乘
Math
.round(maxLen
*a
)/Math
.round(maxLen
*b
)//除
]
let
round = (n
, decimals
= 0) => Number
(`$
{Math
.round(`$
{n
}e$
{decimals
}`
)}e
-$
{decimals
}`
)
let str
= String
(round(tyeps
[type
],digit
))
if(digit
){
if(str
.includes
('.'))return str
.split('.')[0]+'.'+str
.split('.')[1].padEnd
(digit
,0)
return (str
+'.').padEnd
((str
+'.').length
+digit
,0)
}else{
return tyeps
[type
]
}
}
测试用例请往 测试用例 查看
「三年博客,如果觉得我的文章对您有用,请帮助本站成长」
共有 0 条评论 - JavaScript 的精度丢失