JAVA BigDecimal除法精度和格式化輸出

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/zehong1995/article/details/78195506
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class Main {
    public static void main(String[] args) {
        //保留兩位小數
        DecimalFormat df1 = new DecimalFormat("0.00"); 
        DecimalFormat df2 = new DecimalFormat("#.##");
        //0.00表示沒數字位置用0補齊,#。##代表有就有沒有就沒有
        System.out.println(df1.format(0.156));
        System.out.println(df2.format(0.156));

        //高精度實數除法
        MathContext mc = new MathContext(10, RoundingMode.HALF_DOWN); //必須設置精度
        //ROUND_HALF_UP: 遇到0.5的情況時往上近似,例: 1.5 -> 2
        //ROUND_HALF_DOWN : 遇到0.5的情況時往下近似,例: 1.5 -> 1
        BigDecimal a = BigDecimal.valueOf(5.16545213);
        BigDecimal b = BigDecimal.valueOf(1.512345);
        BigDecimal ans = a.divide(b, mc); //高精度整數不用設置精度,實數必須要
        System.out.println(ans);
        System.out.println(df1.format(ans));
    }

}

答案

0.16
0.16
3.415524983
3.42
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章