Method 1: Calculate using Math.round, the number format returned here is
float price=89.89; int itemNum=3; float totalPrice=price*itemNum; float num=(float)(Math.round(totalPrice*100)/100);//如果要求精确4位就*10000然后/10000
Recommended online learning video tutorials: java free video tutorial
Method 2: Use DecimalFormat to return String format. This class comprehensively encapsulates decimal. Such as % sign, thousandth place, decimal precision. Scientific calculation
float price=1.2; DecimalFormat decimalFormat=new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足. String p=decimalFomat.format(price);//format 返回的是字符串
It is recommended to use the second method to display the amount at the front desk because it returns a string format.
Recommended more related java articles and tutorials: Getting started with java
The above is the detailed content of How to make float type data retain two decimal places in java. For more information, please follow other related articles on the PHP Chinese website!