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

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

王林
Release: 2019-11-27 10:16:39
Original
8698 people have browsed it

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
Copy after login

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 返回的是字符串
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template