Java retains two decimal places in four ways, java two decimal places in four ways

Source: Internet
Author: User

Java retains two decimal places in four ways, java two decimal places in four ways
Four Methods for retaining two decimal places in java

Method 1: String format method (recommended)

Double f = 111231.5585;

System. out. println (String. format ("%. 2f", f ));

 

Method 2: format of DecimalFormat

Double f = 111231.5585;

DecimalFormat df = new DecimalFormat ("#. 00 ");
System. out. println (df. format (f ));

 

 

 

 

See the following content.

Method 3: setScale of BigDecimal

Double f = 111231.5585;

BigDecimal bg = new BigDecimal (f );
Double f1 = bg. setScale (2, BigDecimal. ROUND_HALF_UP). doubleValue ();
System. out. println (f1 );

 

Method 4: setMaximumFractionDigits method of NumberFormat

Double f = 111231.5585;

NumberFormat nf = NumberFormat. getNumberInstance ();
Nf. setMaximumFractionDigits (2 );
System. out. println (nf. format (f ));

 

Code:

1 import java. math. bigDecimal; 2 import java. text. decimalFormat; 3 import java. text. numberFormat; 4 public class format {5 double f = 111231.5585; 6 public void m1 () {7 BigDecimal bg = new BigDecimal (f); 8 double f1 = bg. setScale (2, BigDecimal. ROUND_HALF_UP ). doubleValue (); 9 System. out. println (f1); 10} 11/** 12 * DecimalFormat conversion simplest 13 */14 public void m2 () {15 DecimalFormat df = new DecimalFormat ("#. 00 "); 16 System. out. println (df. format (f); 17} 18/** 19 * String. format printing: 20 */21 public void m3 () {22 System. out. println (String. format ("%. 2f ", f); 23} 24 public void m4 () {25 NumberFormat nf = NumberFormat. getNumberInstance (); 26 nf. setMaximumFractionDigits (2); 27 System. out. println (nf. format (f); 28} 29 public static void main (String [] args) {30 format f = new format (); 31 f. m1 (); 32 f. m2 (); 33 f. m3 (); 34 f. m4 (); 35} 36}

 

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.