Java 保留兩位小數 百分數


今天在做簡單題的時候,發現突然忘記Java怎么實現保留兩位小數了,太菜了。

方法一:NumberFormat方法 

import java.text.NumberFormat;
    public static void main(String[] args) {
        int a = 1,b=3;
        double sum = (double)a/b;
        NumberFormat nt = NumberFormat.getPercentInstance();
        System.out.println(nt.format(sum));
    }

輸出結果:33%

直接獲得百分數 方便

要是保留幾位小數還可以

nt.setMinimumFractionDigits(2);

即保留兩位小數

 

方法二:Math.round()

該方法是四舍五入方法,注意負數中會向上取整。

應用:

double sum = (float)a/b;
System.out.println(Math.round(sum * 100)+"%");

 

暫時先記錄到這里


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM