Java float retains two decimal places or decimal places

Source: Internet
Author: User
Tags string format

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 ); //如果要求精确4位就*10000然后/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" ); //构造方法的字符格式这里如果小数不足2位,会以0补足. String p=decimalFomat.format(price); //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.