推奨される解決策
BigDecimal.valueOf (hisDouble).toPlainString ()
この投稿の最後のセクションで提供されたハックは、OP の質問を解決しようとしたときに最初に頭に浮かんだものでした。
その後、友人が私が何をしているのかを尋ね、OP を使用する方が良いと言い、BigDecimal
facepalm モードに入りました..
しかし、このハックをこの投稿に残して、世界が私が時々どれほど愚かであるかを理解できるようにします.
印刷するときに使用できますSystem.out.format
。
以下のスニペットは、 の値をyourDecimal
小数点以下 1 桁に丸め、値を出力します。
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