zhaoyanjun

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

 





 

分类:

技术点:

相关文章:

  • 2021-12-18
  • 2022-01-02
  • 2022-01-02
  • 2021-11-14
  • 2021-11-18
  • 2021-11-28
  • 2021-12-18
猜你喜欢
  • 2021-12-18
  • 2021-10-19
  • 2021-11-14
  • 2022-01-02
  • 2021-10-19
  • 2021-12-23
  • 2021-12-18
相关资源
相似解决方案