我有这个格式化大数字的功能。
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
我想得到3.9 M
,我得到的是3,8 M
,因为算法不会四舍五入到最接近的上限值。我不知道该怎么做。
任何的想法 ?