I want to parse a java double value to string but with dot separator and infinite number of digits after the decimal. What I want to achived:
33.123456789 -> "33.123456789"
1.234 -> "1.234"
2.0 -> "2"
I have my sample code but it doesn't work corectly.
DecimalFormat DOUBLE_FORMAT = (DecimalFormat)NumberFormat.getNumberInstance(Locale.ENGLISH);
DOUBLE_FORMAT.applyPattern("#.####");
Which gives me:
33.123456789 -> "33.1234"
1.234 -> "1.234"
2.0 -> "2"
So it not work how I want to. Any idea ? ;)
Doubles are just an approximation, a sum of 2-i. Hence
33.123456789 * 100 != 3312.3456789
And
double x = 33.123456789;
String s = String.valueOf(x);
// No guarantee that s has the same number of decimals.
And for the precise numerical type BigDecimal:
BigDecimal x = new BigDecimal(33.123456789); // Bad
BigDecimal x = new BigDecimal("33.123456789"); // Good, with correct precision.
So in your case, one must consider switching to BigDecimal. Or accept String.valueOf
/ Double.toString
.
BigDecimal, though, has that unlimited precision.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments