I am not able to understand, why this code retursn 10.0, rather than 10
Double inputDouble = Double.valueOf("10");
System.out.println(inputDouble);
The requirement is
if I pass 10.00, output should be 10.00
if I pass 10.0, output should be 10.0
and if I pass 10, output should be 10
is it possible and in a clean way
The requirement is if I pass 10.00, output should be 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.
You should try using BigDecimal
instead:
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. If you're interested in the actual decimal digits that you're provided with, that's another reason to use BigDecimal
.
See more on this question at Stackoverflow