Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 14th, 2012  |  syntax: None  |  size: 0.91 KB  |  hits: 23  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. How do I make Java format a double like -3.2 rather than -3.1999999999999953?
  2. BigDecimal.valueOf (hisDouble).toPlainString ()
  3.        
  4. Double yourDouble = -3.1999999999999953;
  5. System.out.format ("%.1f", yourDouble);
  6.        
  7. -3.2
  8.        
  9. public static String fixDecimal (Double d) {
  10.     String  str = "" + d;
  11.     int    nDot = str.indexOf ('.');
  12.  
  13.     if (nDot == -1)
  14.       return str;
  15.  
  16.     for (int i = nDot, j=0, last ='?'; i < str.length (); ++i) {
  17.       j = str.charAt (i) == last ? j+1 : 0;
  18.  
  19.       if (j > 3)
  20.         return String.format ("%."+(i-nDot-j-1)+"f", d);
  21.  
  22.       last = str.charAt (i);
  23.     }
  24.  
  25.     return str;
  26.   }
  27.        
  28. Double[] testcases = {
  29.   3.19999999999953,
  30.   3.145963219488888,
  31.   10.4511111112,
  32.   100000.0
  33. };
  34.  
  35. for (int i =0; i < testcases.length; ++i)
  36.   System.out.println (
  37.     fixDecimal (testcases[i]) + "n"
  38.   );
  39.        
  40. 3.2
  41. 3.1459632195
  42. 10.45
  43. 100000.0
  44.        
  45. System.out.println(BigDecimal.valueOf(-3.2d).toPlainString());
  46.        
  47. -3.2