java字符串转bigdecimal,在java中将字符串转换为BigDecimal

本文探讨了在Java中将货币字符串135.69转换为BigDecimal时,为何会得到135.6899999999999977。作者推荐使用BigDecimal(String)或BigDecimal.valueOf(double)避免精度丢失,解释了double类型无法精确表示所有十进制数的原因,并提供了相应构造函数的使用建议。
摘要由CSDN通过智能技术生成

I am reading a currency from XML into Java.

String currency = 135.69;

When I convert this to BigDecimal I get:

System.out.println(new BigDecimal(135.69));

Output:

135.68999999999999772626324556767940521240234375.

Why is it that it outputs this many numbers? How can I avoid this? All I want is for it to output 135.69.

解决方案

The BigDecimal(double) constructor have some problems, is preferrable that you uses BigDecimal(String) or BigDecimal.valueOf(double).

System.out.println(new BigDecimal(135.69)); //135.68999999999999772626324556767940521240234375

System.out.println(new BigDecimal("135.69")); // 135.69

System.out.println(BigDecimal.valueOf(135.69)); // 135.69

The BigDecimal(double) documentation explain about this behavior:

The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.

When a double must be used as a source for a BigDecimal, note that this constructor provides an exact conversion; it does not give the same result as converting the double to a String using the Double.toString(double) method and then using the BigDecimal(String) constructor. To get that result, use the static valueOf(double) method.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值