Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

浮点数精度丢失 #12

Open
wweggplant opened this issue Sep 25, 2023 · 0 comments
Open

浮点数精度丢失 #12

wweggplant opened this issue Sep 25, 2023 · 0 comments

Comments

@wweggplant
Copy link
Owner

不仅仅是javascript的问题——浮点数精度丢失

从熟悉的加法开始

下面的代码我想肯定有不少人都知道,估计也知道这个是犹豫浮点数精度丢失造成的。会下意思的觉得这个是javascript的责任,其实这个问题很多语言都有,比如java等。这个的根本原因是计算器用二进制表示数字,这就导致存放一个数字需要的位数会很长,但是储存的位数是有限的。这就导致必然会发生位数的舍入。

0.1 + 0.2 // 0.30000000000000004
0.3 - 0.1 // 0.19999999999999998

IEEE754标准

很多编程语言都是根据IEEE754标准对数值类型进行处理的。有很多文章把这块讲的很清楚了。

(JavaScript 深入之浮点数精度)[https://github.com/mqyqingfeng/Blog/issues/155]

如何解决精度问题?

简单办法

涉及到金额情况,如果计算比较简单,可以把金额转换成最小单位,然后再存放结果。比如人民币最小单位是分,1元转成分就是100分。那么就存100就好了。涉及到其他币种也类似。

java中

在金融项目中,由于涉及金额这样很重要的数据,试想你的银行账户本来是0.3元,结果变成0.30000000000000004一开始会很高兴,可过了两天本应是0.2元,可是显示的是0.19999999999999998,那心里一定会骂娘吧。可以参考在java中,用BigDecimal类用来处理这类问题。了解了一下BigDecimal的使用方式,主要是把数值构造成BigDecimal类,然后使用它有的api进行的操作。

BigDecimal intStr = new BigDecimal("0.1");
BigDecimal result = intStr.add(new BigDecimal("0.2"));
System.out.println(result.toString());  // 0.3

javascript中

在javascript中也有类似的库

  1. (bignumber)[https://mikemcl.github.io/bignumber.js/]
  2. (decimal)[https://mikemcl.github.io/decimal.js/]
@wweggplant wweggplant changed the title 浮点数精度 浮点数精度丢失 Sep 25, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant