简体   繁体   English

java +将String转换为Double会在小数点后追加尾随零

[英]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.

相关问题 Java中的正则表达式以查找字符串是否为带有尾随零的十进制数字格式 - Regex in java to find if a String is in the format of a decimal number with a trailing zero 在java中错误的十进制从Double转换为String - Wrong Decimal Converting from Double to String in java 在Java中将&lt;0.001的十进制(double)值转换为字符串 - Converting Decimal (Double) Value < 0.001 to String in Java 将字符串转换为双精度时,删除 java 中第一个后的任何多个点或任何小数点 - Remove any multiple points or any decimal points after the first one in java when converting string to double 从双精度中删除十进制后的尾随零 - Remove trailing zeroes after decimal from double 如何在将双精度值转换为字符串后删除小数点 - How to remove decimal point from a double value after converting it to a string 如何在不删除Java中尾随零的情况下找到双精度数字小数点后的长度? - how to find length after decimal point of a double number without removing trailing zeroes in java? 将字符串转换为double [] []-Java - Converting a string into a double[][] - Java Java:将双精度转换为字符串 - Java: Converting a double to a String TreeMap 在小数点后放置带尾随零的 BigDecimal 键无效 - TreeMap putting BigDecimal key with trailing zero after decimal has no effect
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM