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 unpredict
最后
以上就是纯真流沙最近收集整理的关于java字符串转bigdecimal,在java中将字符串转换为BigDecimal的全部内容,更多相关java字符串转bigdecimal内容请搜索靠谱客的其他文章。
发表评论 取消回复