I want to format Java doubles much like String.valueOf(double) does, that is, without loss of precision. But I need to use locale-dependent thousand-separators and would prefer a formatter String, as in String.format. I don't need vertical alignment of several numbers. Examples (in Locale.US):
1.0 -> "1.0"
1.1 -> "1.1"
1.11 -> "1.11"
1000 * Math.PI -> "3,141.592653589793"
1e9 -> "1,000,000,000.0"
1.234567890123e9 -> "1,234,567,890.123"
Any better suggestion than the following hack, involving parsing the result of String.valueOf(d) to calculate the number of decimal places?
double d = ...
String s = String.valueOf(d);
int exponent = s.indexOf('E');
int decimals;
if (0 <= exponent) {
decimals = Math.max(1, exponent - s.indexOf('.') - Integer.parseInt(s.substring(exponent + 1)) - 1);
}
else {
decimals = s.length() - s.indexOf('.') - 1;
}
String format = "%,." + decimals + "f";
System.out.printf("Value: " + format + "\n", d);
ymene's answer that you would like a validString.formatformat string, take a look at this question onString.formatvariable precision. In all likelihood, you're probably not going to get any better than what you already have unless you can remove theString.formatrestriction and use, for example,NumberFormat.