BigDecimal类计算不精确问题

qq_31134691 2015-10-08 06:28:16
import java.math.*;
import java.text.*;
import java.util.*;

public class Test8 {
public static void main(String[] args) {
BigDecimal bg1 = new BigDecimal(100.91);
BigDecimal bg2 = new BigDecimal(5);
BigDecimal bg3 = bg1.multiply(bg2);

System.out.println(bg3); //输出504.549999999999982946974341757595539093017578125?为什么
}
}
...全文
206 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
tony4geek 2015-10-10
  • 打赏
  • 举报
回复
上面 1楼写在很清晰。你传入string 进去。
tony4geek 2015-10-10
  • 打赏
  • 举报
回复
Note: the results of this constructor can be somewhat unpredictable. One might assume that new BigDecimal(.1) is exactly equal to .1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625. This is so because .1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to .1, appearances nonwithstanding. The (String) constructor, on the other hand, is perfectly predictable: new BigDecimal(".1") is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one.
qq_31134691 2015-10-10
  • 打赏
  • 举报
回复
换成Sring为参数就能提高精确度了是么?
飏飏一蝶 2015-10-08
  • 打赏
  • 举报
回复
BigDecimal(double val) Translates a double into a BigDecimal. BigDecimal(String val) Translates the String repre sentation of a BigDecimal into a BigDecimal. Note: the results of this constructor can be somewhat unpredictable. One might assume that new BigDecimal(.1) is exactly equal to .1, but it is actually equal to .1000000000000000055511151231257827021181583404541015625. This is so because .1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the long value that is being passed in to the constructor is not exactly equal to .1, appearances nonwithstanding. The (String) constructor, on the other hand, is perfectly predictable: new BigDecimal(".1") is exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String) constructor be used in preference to this one. 就因为即便你写的是100.91,计算机二进制也没法精确表示(小数点后一直乘2,根本没法到刚好合适的时候,即没法转换成有限的二进制表示),所以你用BigDecimal包装下也是不精确的,推荐用第二个构造函数 BigDecimal bg1 = new BigDecimal(“100.91”); 5是int型,肯定是可以用二进制精确表示的

50,544

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧