数值金额计算js封装包含加减乘除四个方法,能确保浮点数运算不丢失精度。

项目场景:

商城类项目中大多需要金额计算,我们知道计算机编程语言里浮点数计算会存在精度丢失问题(或称舍入误差),其根本原因是二进制和实现位数限制有些数无法有限表示

以下是十进制小数对应的二进制表示:
0.1 >> 0.0001 1001 1001 1001…(1001无限循环)
0.2 >> 0.0011 0011 0011 0011…(0011无限循环)
计算机里每种数据类型的存储是一个有限宽度,比如 JavaScript 使用 64 位存储数字类型,因此超出的会舍去。舍去的部分就是精度丢失的部分。
如果直接加减乘除:
0.1 + 0.2 == 0.30000000000000004 (多了 0.00000000000004)
0.2 + 0.4 == 0.6000000000000001 (多了 0.0000000000001)
19.9 * 100 == 1989.9999999999998 (少了 0.0000000000002)
所以要精确计算需要进行处理,,实现加减乘除运算,确保不丢失精度

解决方案:

/**
 * 判断是否为一个整数
 * @param {object} obj 字符串
 * @return {boolean} true/false
 */
export function isInteger(obj) {
    return Math.floor(obj) === obj;
}

/**
 * 将一个浮点数转成整数,返回整数和倍数。如 3.14 >> 314,倍数是 100
 * @param {object} floatNum 小数
 * @return {object} {times:100, num: 314}
 */
export function toInteger(floatNum) {
    var ret = { times: 1, num: 0 }
    var isNegative = floatNum < 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(Math.abs(floatNum) * times + 0.5, 10)
    ret.times = times
    if (isNegative) {
        intNum = -intNum
    }
    ret.num = intNum
    return ret
}

/**
 * 浮点型数字运算精度丢失修复
 * @param {object} num 小数
 * @param {number} s 小数位数
 * @return {object} s位小数
 */
export function toFixed(num, s) {
    var times = Math.pow(10, s);
    var des = num * times + 0.5;
    des = (parseInt(des, 10) / times) + '';

    var pos_decimal = des.indexOf('.');
    if (pos_decimal > 0) {
        while (des.length <= pos_decimal + s) {
            des += '0';
        }
    }

    return des;
}

/**
 * 浮点型数字运算精度丢失修复
 * 核心方法,实现加减乘除运算,确保不丢失精度
 * 思路:把小数放大为整数(乘),进行算术运算,再缩小为小数(除)
 * @param a {number} 运算数1
 * @param b {number} 运算数2
 * @param dig {number} 精度,保留的小数点数,比如 2, 即保留为两位小数
 * @param op {string} 运算类型,有加减乘除(add/subtract/multiply/divide)
 * @return {object} dig位小数
 */
function operation(a, b, dig, op) {
    var o1 = toInteger(a)
    var o2 = toInteger(b)
    var n1 = o1.num
    var n2 = o2.num
    var t1 = o1.times
    var t2 = o2.times
    var max = t1 > t2 ? t1 : t2
    var result = null
    switch (op) {
        case 'add':
            if (t1 === t2) { // 两个小数位数相同
                result = n1 + n2
            } else if (t1 > t2) { // o1 小数位 大于 o2
                result = n1 + n2 * (t1 / t2)
            } else { // o1 小数位 小于 o2
                result = n1 * (t2 / t1) + n2
            }
            return toFixed(result / max, dig)
        case 'subtract':
            if (t1 === t2) {
                result = n1 - n2
            } else if (t1 > t2) {
                result = n1 - n2 * (t1 / t2)
            } else {
                result = n1 * (t2 / t1) - n2
            }
            return toFixed(result / max, dig)
        case 'multiply':
            result = (n1 * n2) / (t1 * t2)
            return toFixed(result, dig)
        case 'divide':
            if (n2 === 0)
                result = 0
            else
                result = (n1 / n2) * (t2 / t1)
            return toFixed(result, dig)
    }
}

/**
 * 加法
 * @param a {number} 运算数1
 * @param b {number} 运算数2
 * @return {object} s位小数
 */
export function add(a, b, s) {
    return operation(a, b, (s | 2), 'add')
}

/**
 * 减法
 * @param a {number} 运算数1
 * @param b {number} 运算数2
 * @return {object} s位小数
 */
export function subtract(a, b, s) {
    return operation(a, b, (s | 2), 'subtract')
}

/**
 * 乘法
 * @param a {number} 运算数1
 * @param b {number} 运算数2
 * @return {object} s位小数
 */
export function multiply(a, b, s) {
    return operation(a, b, (s | 2), 'multiply')
}

/**
 * 除法
 * @param a {number} 运算数1
 * @param b {number} 运算数2
 * @return {object} s位小数
 */
export function divide(a, b, s) {
    return operation(a, b, (s | 2), 'divide')
}

上面的为math.js文件,封装到这里面然后引用
vue中引用使用方法:
main.js:
import * as math from ‘./utils/math’//引入js
Vue.prototype.math = math

使用:
this.math.add(this.numberCases, this.Number)

标签中引用:

{{math.multiply(item.Discount, item.Num)}}

  • 37
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个Java封装大整数类型计算的工具类,支持加减乘除运算: ``` import java.math.BigInteger; public class BigNumUtil { /** * 加法运算 * @param num1 第一个大整数 * @param num2 第二个大整数 * @return 两个大整数的和 */ public static String add(String num1, String num2) { // 将字符串转换为BigInteger类型,并进行加法运算 BigInteger bigNum1 = new BigInteger(num1); BigInteger bigNum2 = new BigInteger(num2); BigInteger result = bigNum1.add(bigNum2); return result.toString(); } /** * 减法运算 * @param num1 被减数 * @param num2 减数 * @return 两个大整数的差 */ public static String subtract(String num1, String num2) { // 将字符串转换为BigInteger类型,并进行减法运算 BigInteger bigNum1 = new BigInteger(num1); BigInteger bigNum2 = new BigInteger(num2); BigInteger result = bigNum1.subtract(bigNum2); return result.toString(); } /** * 乘法运算 * @param num1 第一个大整数 * @param num2 第二个大整数 * @return 两个大整数的积 */ public static String multiply(String num1, String num2) { // 将字符串转换为BigInteger类型,并进行乘法运算 BigInteger bigNum1 = new BigInteger(num1); BigInteger bigNum2 = new BigInteger(num2); BigInteger result = bigNum1.multiply(bigNum2); return result.toString(); } /** * 除法运算 * @param num1 被除数 * @param num2 除数 * @return 两个大整数的商 */ public static String divide(String num1, String num2) { // 将字符串转换为BigInteger类型,并进行除法运算 BigInteger bigNum1 = new BigInteger(num1); BigInteger bigNum2 = new BigInteger(num2); BigInteger result = bigNum1.divide(bigNum2); return result.toString(); } } ``` 使用示例: ``` public class Test { public static void main(String[] args) { String num1 = "12345678901234567890"; String num2 = "98765432109876543210"; System.out.println(BigNumUtil.add(num1, num2)); // 111111111111111111100 System.out.println(BigNumUtil.subtract(num1, num2)); // -86419753208641975320 System.out.println(BigNumUtil.multiply(num1, num2)); // 1219326311370217951367253019726675650416900 System.out.println(BigNumUtil.divide(num1, "3")); // 4115226300411526300 } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

野猪佩奇007

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值