保留两位小数(不四舍五入)方法:
public static String calculateProfit(double doubleValue) {
// 保留4位小数
DecimalFormat df = new DecimalFormat("0.0000");
String result = df.format(doubleValue);
// 获取小数 . 号第一次出现的位置
int index = firstIndexOf(result, ".");
// 字符串截断
return result.substring(0, index + 3);
}
public static int firstIndexOf(String str, String pattern) {
for (int i = 0; i < (str.length() - pattern.length()); i++) {
int j = 0;
while (j < pattern.length()) {
if (str.charAt(i + j) != pattern.charAt(j))
break;
j++;
}
if (j == pattern.length())
return i;
}
return -1;
}