java - 在java中将字符串转换为BigDecimal

标签 java bigdecimal

我正在将一种货币从 XML 读入 Java。

String currency = "135.69";

当我将其转换为 BigDecimal 时,我得到:

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

输出:

135.68999999999999772626324556767940521240234375.

为什么会输出这么多数字?我怎样才能避免这种情况?我只想让它输出 135.69。

最佳答案

BigDecimal(double) 构造函数可能具有不可预测的行为。最好使用 BigDecimal(String) 或 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

BigDecimal(double) 的文档详细解释:

  1. 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.
  2. 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.
  3. 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.

关于java - 在java中将字符串转换为BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28783918/

相关文章:

java - 在没有数组的情况下对四个数字进行排序

java - 将位转换为 double 后,如何在不使用 BigDecimal 的情况下存储实际的浮点/ double 值?

从 Oracle 数据库获取 float 时出现 Java 精度问题 - 无法正确舍入

java - 有没有办法将整个 Big Decimals 列表转换为 Long 值列表

java - 将 BigDecimal 舍入到最接近的 5 美分

java - 设置 BigDecimal 的特定精度

java - XStream 可序列化对象

java - XML DOM setNodeValue ("") 在文本节点上,还会删除其包含元素的开始标记

java - 无法移除组件并重新绘制

java - 序列化器 - Kryo 的速度、API/功能(如 FlexJson)