Double 数据保留两位小数二:直接截取小数后面两位,不进行四舍五入 相关的博客:Double 数据保留两位小数一:五舍六入


package
com; public class T2 { public static void main(String[] args) { System.out.println(calculateProfit(0)); System.out.println(calculateProfit(0.963)); System.out.println(calculateProfit(0.123456)); System.out.println(calculateProfit(100)); System.out.println(calculateProfit(.9654)); } /** * 保留double类型小数后两位,不四舍五入,直接取小数后两位 比如:10.1269 返回:10.12 * * @param doubleValue * @return */ public static String calculateProfit(double doubleValue) { // 保留4位小数 java.text.DecimalFormat df = new java.text.DecimalFormat("#.0000"); String result = df.format(doubleValue); // 截取第一位 String index = result.substring(0, 1); if (".".equals(index)) { result = "0" + result; } // 获取小数 . 号第一次出现的位置 int inde = firstIndexOf(result, "."); // 字符串截断 return result.substring(0, inde + 3); } /** * 查找字符串pattern在str中第一次出现的位置 * * @param str * @param pattern * @return */ 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; } }

运行结果:

0.00
0.96
0.12
100.00
0.96