js 计算丢失精度问题
由于js无法精准计算带有小数点的值。
所以先把小数点去掉(去掉小数点用字符串替换,如果使用乘以10的倍数,依然出现计算不精确问题)
解决:
加法 & 减法 : 求出两数最长的小数位数 n,做10的 n 次方
代码 :
const str1 = 123456.78
const str2 = 456789.1234
//小数位数
const num1 = str1.split('').reverse().indexOf('.')
const num2 = str1.split('').reverse().indexOf('.')
// 求最长的小数位 做幂次方运算( Math.pow(x,y) 返回x的y次方;Math.max(x,y) 返回最大值 )
const maxTimes = Math.pow(10,Math.max(num1,num2))
return (str1*maxTimes (+ || -) str2*maxTimes)/maxTimes
//乘法中每一项都乘以公积数,所以结果要除以公积数的平方
return (str1*maxTimes * str2*maxTimes) / (maxTimes * maxTimes)
// 除法随便。
return (str1*maxTimes / str2*maxTimes)
知识点:
str.indexOf(x) 该方法返回某个元素在数组中的位置 || 返回某个指定的字符串值在字符串中首次出现的位置
例:"12345".indexOf("3") 返回应该是2, 表示"3" 在"12345" 的下标是2。字符串下标从0开始
str.split('') 将每一个字符拆分组成一个数组 "12345".split('') 返回 ['1', '2', '3', '4', '5']
arr.reverse() 将数组倒序 ['1', '2', '3', '4', '5'].reverse() 返回 ['5', '4', '3', '2', '1']
原理总结
将字符串转为数组,然后去倒序,此时获取 点 的下标就是小数点的位数。