title: Java format string for precise doubles?
body: <p>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):</p>
  
  <pre><code>1.0 -&gt; "1.0"
  1.1 -&gt; "1.1"
  1.11 -&gt; "1.11"
  1000 * Math.PI -&gt; "3,141.592653589793"
  1e9 -&gt; "1,000,000,000.0"
  1.234567890123e9 -&gt; "1,234,567,890.123"
  </code></pre>
  
  <p>Any better suggestion than the following hack, involving parsing the result of String.valueOf(d) to calculate the number of decimal places?</p>
  
  <pre><code>double d = ...
  String s = String.valueOf(d);
  int exponent = s.indexOf('E');
  int decimals;
  if (0 &lt;= 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);
  </code></pre>