參考文章:
https://www.cnblogs.com/wangpei/p/4756055.html
https://blog.csdn.net/dongapple/article/details/76974624
一、需要使用BigDecimal來實現
1 package com.cy.test.math; 2 3 import java.math.BigDecimal; 4 5 public class TestJiSuan { 6 7 public static void main(String[] args) { 8 double a = 1; 9 double b = 3; 10 double c = a / b; 11 System.out.println(c); //0.3333333333333333 12 System.out.println(divide(a, b, 2)); //0.33 13 14 int total = 21; 15 int count = 9; 16 double average = total / count; 17 System.out.println(average); //2.0 18 System.out.println((double)total); //21.0 19 System.out.println(divide((double)total, (double)count, 2)); //2.33 20 } 21 22 /** 23 * 兩個double類型的數相除,保留兩位小數 24 * @param a 25 * @param b 26 * @param scale 27 * @return 28 */ 29 public static double divide(double a, double b, int scale){ 30 BigDecimal bd1 = new BigDecimal(Double.toString(a)); 31 BigDecimal bd2 = new BigDecimal(Double.toString(b)); 32 return bd1.divide(bd2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); 33 } 34 }
二、DecimalFormat
參考文章:https://www.jb51.net/article/135720.htm
/** * 計算結果百分比,保留1位小數 * * @param a 除數 * @param b 被除數 * @return */ private static String calculateResultOfPercent(Integer a, Integer b) { if (b == 0) { return "0%"; } DecimalFormat df = new DecimalFormat("#.#%"); return df.format((double) a / b); }
---
