1. 程式人生 > >Java float保留兩位小數或多位小數

Java float保留兩位小數或多位小數

plain ima itl highlight border 十進制 syn 兩位小數 ice

方法1:用Math.round計算,這裏返回的數字格式的.

1 2 3 4 float price=89.89; int itemNum=3; float totalPrice=price*itemNum; float num=(float)(Math.round(totalPrice*100)/100);//如果要求精確4位就*10000然後/10000

方法2:用DecimalFormat 返回的是String格式的.該類對十進制進行全面的封裝.像%號,千分位,小數精度.科學計算.

1 2 3 float price=1.2; DecimalFormat decimalFormat=
new DecimalFormat(".00");//構造方法的字符格式這裏如果小數不足2位,會以0補足. String p=decimalFomat.format(price);//format 返回的是字符串

第二種方式是字符串格式的.

Java float保留兩位小數或多位小數