3 回答
TA贡献1785条经验 获得超8个赞
格式化为String是一项昂贵的操作(在性能方面),这可以通过数学运算来完成:
double x = 49455.10937;
x *= 100; // moves two digits from right to left of dec point
x = Math.floor(x); // removes all reminaing dec digits
x /= 100; // moves two digits from left to right of dec point
TA贡献1829条经验 获得超9个赞
double decimalValue = 49455.10937;
String decimalValueStr = String.valueOf(decimalValue);
int indexDot = decimalValueStr.lastIndexOf('.');
int desiredDigits=3;
String decimal = decimalValueStr.substring(0, (indexDot + 1) + desiredDigits);
decimalValue = Double.parseDouble(decimal);
System.out.println(decimalValue);
//49455.109 is console output (change desired digits)
TA贡献1951条经验 获得超3个赞
您可以使用格式化程序来格式化双精度值,如下所示
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb, Locale.US);
Double value = 49455.10937;
System.out.println(formatter.format("The value: %.2f", value));
添加回答
举报
