當我們輸出的小數不知道有幾位小數,也不知道后面有沒有帶零,去掉后面多余零可以采用以下方法。在實際使用中,多用於小數轉百分數,百分數前面的小數乘以100后轉String輸出,輸出的String很多帶零,可以用此方法先去掉小數多余的零再轉String。
1 DecimalFormat decimalFormat = new DecimalFormat("###.##"); 2 float a = 0.3450f; 3 float b = 0.0123f; 4 float c = 3.001234f; 5 String d=decimalFormat.format(a); 6 String e=decimalFormat.format(b); 7 String f=decimalFormat.format(c); 8 System.out.println(d);//0.34 9 System.out.println(e);//0.01 10 System.out.println(f);//3