How Java makes float retain 2 or more decimal places

Source: Internet
Author: User

Tag: Print Select Pre target indicates 0.12. Text Mat blank

Method 1:


float F = 34.232323;
BigDecimal B = new BigDecimal (f);
Float F1 = B.setscale (2, bigdecimal.round_half_up). Floatvalue ();
B.setscale (2, bigdecimal.round_half_up) indicates rounding, reserving two decimal places

  float ft   =  134.3435f;     int   Scale  =   2;   Set the number  of digits  int   roundingmode  =  4;   indicates rounding, you can choose other values, such as the tail, and so  on.  BigDecimal   bd  =   new  BigDecimal (double) ft);    BD   =  bd.setscale (scale,roundingmode);    FT   =  

Method 2:

Import Java.text.DecimalFormat;
String a = new DecimalFormat ("###,###,###.##"). Format (100.12345);

That

  float   Scale  =   34.236323;   DecimalFormat   fnum  =   new  DecimalFormat ("# #0. xx");    String   dd=Fnum.format (scale);      SYSTEM.OUT.PRINTLN (DD);  

Method 3: The simplest method

   float   A  =   123.2334f;        float  b   =  (float) (Math.Round (a*100))/100; (Here's 100 is the 2-bit decimal point, if you want to other bits, such as 4 bits, here two 100 is changed to 10000)

How Java makes float retain 2 or more decimal places

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.