
Untitled
By: a guest on
May 14th, 2012 | syntax:
None | size: 0.91 KB | hits: 23 | expires: Never
How do I make Java format a double like -3.2 rather than -3.1999999999999953?
BigDecimal.valueOf (hisDouble).toPlainString ()
Double yourDouble = -3.1999999999999953;
System.out.format ("%.1f", yourDouble);
-3.2
public static String fixDecimal (Double d) {
String str = "" + d;
int nDot = str.indexOf ('.');
if (nDot == -1)
return str;
for (int i = nDot, j=0, last ='?'; i < str.length (); ++i) {
j = str.charAt (i) == last ? j+1 : 0;
if (j > 3)
return String.format ("%."+(i-nDot-j-1)+"f", d);
last = str.charAt (i);
}
return str;
}
Double[] testcases = {
3.19999999999953,
3.145963219488888,
10.4511111112,
100000.0
};
for (int i =0; i < testcases.length; ++i)
System.out.println (
fixDecimal (testcases[i]) + "n"
);
3.2
3.1459632195
10.45
100000.0
System.out.println(BigDecimal.valueOf(-3.2d).toPlainString());
-3.2