概述
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,在java中将字符串转换为BigDecimal所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复