当前位置:网站首页>在小程序中关于js数字精度丢失的解决办法
在小程序中关于js数字精度丢失的解决办法
2022-08-05 05:29:00 【weixin_43923808】
我们在计算 0.1 + 0.1 正确结果是 0.2,但是计算 0.1 + 0.2 的结果并不是0.3,而是0.30000000000000004,0.58*100应该是58却显示57.999999999999999
这是由于JS 数字丢失精度的原因
方式一:
var aa=parseFloat((0.1 + 0.2).toPrecision(12))//12为保留几位小数
var bb=parseFloat((0.58 * 100).toPrecision(12))
console.log(aa, 'aa')
console.log(bb, 'bb') 
方式二:(推荐)


解决方式:把小数放到位整数(乘倍数),再缩小回原来倍数(除倍数)
//如: 0.1 + 0.2
(0.1*10 + 0.2*10) / 10 == 0.3 // true我在utils文件夹下新建public_fun.js一个作为公用文件

public_fun.js内容如下
/*
* 判断obj是否为一个整数
*/
function isInteger(obj) {
return Math.floor(obj) === obj
}
/*
* 将一个浮点数转成整数,返回整数和倍数。如 3.14 >> 314,倍数是 100
* @param floatNum {number} 小数
* @return {object}
* {times:100, num: 314}
*/
function toInteger(floatNum) {
var ret = { times: 0, num: 0 }
if (isInteger(floatNum)) {
ret.num = floatNum
return ret
}
var strfi = floatNum + ''
var dotPos = strfi.indexOf('.')
var len = strfi.substr(dotPos + 1).length
var times = Math.pow(10, len)
var intNum = parseInt(floatNum * times + 0.5, 10)
ret.times = times
ret.num = intNum
return ret
}
/*
* 核心方法,实现加减乘除运算,确保不丢失精度
* 思路:把小数放大为整数(乘),进行算术运算,再缩小为小数(除)
*
* @param a {number} 运算数1
* @param b {number} 运算数2
* @param digits {number} 精度,保留的小数点数,比如 2, 即保留为两位小数
* @param op {string} 运算类型,有加减乘除(add/subtract/multiply/divide)
*
*/
function operation(a, b, digits, op) {
var o1 = toInteger(a)
var o2 = toInteger(b)
var max = o1.times > o2.times ? o1.times : o2.times
var result = null
switch (op) {
case 'add':
result = o1.num + o2.num
break
case 'subtract':
result = o1.num - o2.num
break
case 'multiply':
result = o1.num * o2.num
break
case 'divide':
result = o1.num / o2.num
break
}
return result / max
}
// 加减乘除的四个接口
function add(a, b, digits) {
return operation(a, b, digits, 'add')
}
function subtract(a, b, digits) {
return operation(a, b, digits, 'subtract')
}
function multiply(a, b, digits) {
return operation(a, b, digits, 'multiply')
}
function divide(a, b, digits) {
return operation(a, b, digits, 'divide')
}
export {
add,
subtract,
multiply,
divide
}

使用:
在需要用到的页面导入
import * as floatNum from '@/utils/public_fun'使用

结果

方式二:
边栏推荐
猜你喜欢
随机推荐
Chengyun Technology was invited to attend the 2022 Alibaba Cloud Partner Conference and won the "Gathering Strength and Going Far" Award
el-autocomplete use
大小屏适配
document.querySelector() method
盒子模型小练习
NB-IOT智能云家具项目系列实站
lingo入门——河北省第三届研究生建模竞赛B题
指针常量与常量指针 巧记
cs231n学习记录
D39_Eulerian Angles and Quaternions
滚动条问题,未解决
vs2017关于函数命名方面的注意事项
Programmers should understand I/O this way
DevOps - Understanding Learning
selenium学习
Mina disconnects and reconnects
【考研结束第一天,过于空虚,想对自己进行总结一下】
js 使用雪花id生成随机id
浏览器兼容汇总
文本样式这一篇文章就够了









