[英]java + converting String to Double appends trailing zero after decimal
I am not able to understand, why this code retursn 10.0, rather than 10 我不明白,为什么这段代码会折回10.0,而不是10
Double inputDouble = Double.valueOf("10");
System.out.println(inputDouble);
The requirement is if I pass 10.00, output should be 10.00 要求是如果我通过10.00,输出应该是10.00
if I pass 10.0, output should be 10.0 如果我通过10.0,输出应该是10.0
and if I pass 10, output should be 10 如果我通过10,输出应该是10
is it possible and in a clean way 有可能并且以干净的方式
The requirement is if I pass 10.00, output should be 10.00 要求是如果我通过10.00,输出应该是10.00
Then you're using the wrong type. 然后您使用了错误的类型。 double
has no notion of significant digits - there's no difference between 10, 10.0 and 10.00. double
没有有效数字的概念-10、10.0和10.00之间没有区别。
You should try using BigDecimal
instead: 您应该尝试使用BigDecimal
代替:
System.out.println(new BigDecimal("10")); // Prints 10
System.out.println(new BigDecimal("10.0")); // Prints 10.0
System.out.println(new BigDecimal("10.00")); // Prints 10.00
Aside from anything else, even if double
did try to preserve insignificant digits, it would be thinking about binary digits as it's a floating binary point type. 除了其他方面,即使double
确实尝试保留无关紧要的数字,它也会考虑使用二进制数字,因为它是浮点型二进制点类型。 If you're interested in the actual decimal digits that you're provided with, that's another reason to use BigDecimal
. 如果您对所提供的实际十进制数字感兴趣,这是使用BigDecimal
的另一个原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.