保留有效位数的算法
/** * 保留有效位数 * @param s 原始数据 * @param significantDigit 需要保留的有效位数 * @return 保留significantDigit位后的数 */ private String handleSignificantDigit(String s, int significantDigit) { int length = s.length(); int i = 0; while (i < length) { if (s.charAt(i) == '.') { break; } i++; } if ((length - i - 1) <= significantDigit) { StringBuilder sb = new StringBuilder(s); for (int j = 0; j < significantDigit - (length - i - 1); j++) { sb.append('0'); } return sb.toString(); } else { if (s.charAt(i + significantDigit + 1) < '4') { return s.substring(i + significantDigit + 1); } else { double num = Double.parseDouble(s); StringBuilder pattern = new StringBuilder("0."); for (int j = 0; j < significantDigit; j++) { pattern.append('0'); } DecimalFormat decimalFormat = new DecimalFormat(pattern.toString()); String tmp = decimalFormat.format(num); return tmp; } } }