java与javascript精度计算

一、java精度计算

java的数据类型对长度有限制,在进行较大金额计算或者小数位较多时,需要用BigDecimal来处理这种精度问题。

public static void main(String[] args)
    {
        BigDecimal a = new BigDecimal("4.5");
        BigDecimal b = new BigDecimal("1.5");

        System.out.println("a + b =" + a.add(b));
        System.out.println("a - b =" + a.subtract(b));
        System.out.println("a * b =" + a.multiply(b));
        System.out.println("a / b =" + a.divide(b));
    }

二、javascript精度计算

对于JavaScript则容易出现以下问题

0.1 + 0.2 
=> 0.30000000000000004
 
6.8 -0.9
=> 5.8999999999999995
 
7 * 0.8
=> 5.6000000000000005
 
5.6 / 0.8
=> 6.999999999999999
 

这是因为计算机内部计算,都是使用2进制数,而当js将我们使用的10进制转化为2进制数时,由于其遵循IEEE 754的国际标准,无法精确表示这种包含小数点的数据,因此JS将浮点数转换成了用二进制表示的最接近的近似值,这步操作就是导致误差的原因。

解决方案是:定一个函数对计算结果进行转换和处理:通过将浮点数转换成整数进行计算,然后再将整数的小数点位调整,转回正确的浮点数结果。
 

此外:浮点数运算精度丢失问题并不是js独有的!只是诸如 C++/C#/Java 这些语言中已经封装好了方法来避免精度的问题。

// type1: 导库:npm install decimal.js
const Decimal = require('decimal.js');
console.log(Decimal(66.6667).plus(Decimal(33.3333)))//100

// type2: 导库:npm install big.js
const Big = require('big.js');
console.log(Big(66.6667).plus(Big(33.3333)).toNumber())//100

// type3: 导库:npm install mathjs
const Math = require('mathjs');
const mathResult = Math.chain(66.6667)
	.add(33.3333)
	.done()
console.log(mathResult)//100

// type4: 导库:npm install bignumber.js
const BigNumber = require('bignumber.js');
console.log(BigNumber(66.6667).plus(BigNumber(33.3333)).toNumber())//100

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

流星雨在线

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

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

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

打赏作者

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

抵扣说明:

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

余额充值