java保留小數點,數字格式化


注意:

  1、整數除法會取整,不會保留小數點,需要保留小數,轉為float在除

 

方法1、使用字符串格式化

public static float computePercentage(float a, float total) {
    if (a == 0 || total == 0) {
        return 0;
    } else {
        //4表示保留兩位小數,f表示float類型,
        //乘100是因為我是求百分比,
        return Float.parseFloat(String.format("%.4f", a / total)) * 100;
    }
}
測試:System.err.println(computePercentage(141,173));
輸出:81.5

方法二、使用java.text.NumberFormat,數字格式化

  NumberFormat nf=NumberFormat.getNumberInstance();

  //設置最大保留小數點位數
  nf.setMaximumFractionDigits(2);
  float s=(float)141/(float)173;
  System.err.println(nf.format(s));

  輸出:0.82

  注:NumberFormat 還提供了百分比,整數格式化等。

 

方法三、使用DecimalFormat格式化

  float s=(float)141/(float)173;

  //#:以為阿拉伯數字,沒有則不顯示,0:一位阿拉伯數字,沒有用0表示,
  System.err.println(new DecimalFormat("##.00%").format(s));

  輸出:81.50%

 


免責聲明!

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



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