Java retains two decimal places 4 ways
Method One: The Format method of string (recommended)
Double F = 111231.5585;
System.out.println (String.Format ("%.2f", f));
Method Two: The Format method of DecimalFormat
Double F = 111231.5585;
DecimalFormat df = new DecimalFormat ("#.00");
System.out.println (Df.format (f));
Here's what you can do without looking at it
Method Three: The Setscale method 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 Four: The Setmaximumfractiondigits method of NumberFormat
Double F = 111231.5585;
NumberFormat NF = numberformat.getnumberinstance ();
Nf.setmaximumfractiondigits (2);
System.out.println (Nf.format (f));
Code:
1 ImportJava.math.BigDecimal;2 ImportJava.text.DecimalFormat;3 ImportJava.text.NumberFormat;4 Public classFormat {5 Doublef = 111231.5585;6 Public voidM1 () {7BigDecimal BG =NewBigDecimal (f);8 DoubleF1 = Bg.setscale (2, bigdecimal.round_half_up). Doublevalue ();9 System.out.println (F1);Ten } One /** A * DecimalFormat conversion is the easiest - */ - Public voidm2 () { theDecimalFormat DF =NewDecimalFormat ("#.00"); - System.out.println (Df.format (f)); - } - /** + * String.Format Printing is the easiest - */ + Public voidm3 () { ASystem.out.println (String.Format ("%.2f", F)); at } - Public voidM4 () { -NumberFormat NF =numberformat.getnumberinstance (); -Nf.setmaximumfractiondigits (2); - System.out.println (Nf.format (f)); - } in Public Static voidMain (string[] args) { -Format F =Newformat (); to f.m1 (); + f.m2 (); - f.m3 (); the f.m4 (); * } $}
Java retains two decimal places 4 ways