Home  >  Article  >  Java  >  How to make float type data retain two decimal places in java

How to make float type data retain two decimal places in java

王林
王林Original
2019-11-27 10:16:398643browse

How to make float type data retain two decimal places in java

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn