大きな数字をフォーマットするこの関数があります。
public static String ToEngineeringNotation(Double d, String unit, int decimals) {
double exponent = Math.log10(Math.abs(d));
if (d != 0)
{
String result = "0";
switch ((int)Math.floor(exponent))
{
case -2: case -1: case 0: case 1: case 2:
result = (d + "").replace(".", ",") + " " + unit;
break;
case 3: case 4: case 5:
result = ((d / 1e3) + "").replace(".", ",") + " k" + unit;
break;
case 6: case 7: case 8:
result = ((d / 1e6) + "").replace(".", ",") + " M" + unit;
break;
default:
result = ((d / 1e9) + "").replace(".", ",") + " G" + unit;
break;
}
if (result.contains(",")) {
if (result.indexOf(" ") - result.indexOf(",") >= decimals) {
result = result.substring(0, result.indexOf(",") + decimals + 1) + result.substring(result.indexOf(" "));
}
if (decimals <= 0)
result = result.replace(",", "");
}
return result;
} else {
return "0 " + unit;
}
}
3866500.0
I want to getを与えると3.9 M
、代わりに is を取得3,8 M
します。これは、アルゴリズムが最も近い上限値に丸められないためです。どうすればいいのかわかりません。
何か案が ?