Java float retains two decimal places or decimal places

Source: Internet
Author: User
Tags string format

Turn from:Java float retains two decimal places or decimal places

Method 1: Use Math.Round to calculate the number format that is returned here.

float price=89.89;int itemnum=3;float totalprice=price*itemnum;float num= (float) (Math.Round (totalprice*100)/100); /If the exact 4-bit is required *10000 then/10000

Method 2: Return with DecimalFormat in string format. The class is fully encapsulated in decimal. Like the% number, thousand bits, decimal precision. Scientific calculation.

float Price=1.2;decimalformat decimalformat=new DecimalFormat (". 00");//character format of the constructor method if the decimal place is less than 2 bits, it will be filled with 0. String P=decimalfomat.format (price);//format returns a string

I think the second way is to show the amount in the foreground. The reason is simple in string format.

Java float retains two decimal places or decimal places

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.