Double x1 = 0.026;
String format = String.Format ("%.2f", X1);
SYSTEM.OUT.PRINTLN (format);
String format = String.Format ("%.nf", X1);
N: Number of reserved digits (rounded)
Package com.clzhang.sample;
Import Java.math.BigDecimal;
Import Java.math.RoundingMode;
Import Java.text.DecimalFormat;
Import Java.text.NumberFormat;
public class Doubletest {
/**
* Keep two decimal places, rounding up an old-fashioned way
* @param D
* @return
*/
public static double FormatDouble1 (double D) {
Return (double) Math.Round (d*100)/100;
}
/**
* The BigDecimal class provides operations for arithmetic, scale manipulation, rounding, comparison, hashing, and format C Onversion.
* @param D
* @return
*/
public static double FormatDouble2 (double D) {
Old methods that are no longer recommended for use
BigDecimal bg = new BigDecimal (d). Setscale (2, bigdecimal.round_half_up);
New method, if rounding is not required, you can use Roundingmode.down
BigDecimal bg = new BigDecimal (d). Setscale (2, roundingmode.up);
return Bg.doublevalue ();
}
/**
* NumberFormat is the abstract base class for all number formats.
* This class provides the interface for formatting and parsing numbers.
* @param D
* @return
*/
public static String FormatDouble3 (double D) {
NumberFormat NF = numberformat.getnumberinstance ();
Keep Two decimal places
Nf.setmaximumfractiondigits (2);
If rounding is not required, you can use the Roundingmode.down
Nf.setroundingmode (roundingmode.up);
Return Nf.format (d);
}
/**
* This method is quite simple.
* DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers.
* @param D
* @return
*/
public static String FormatDouble4 (double D) {
DecimalFormat df = new DecimalFormat ("#.00");
Return Df.format (d);
}
/**
* This method is quite handy if you are only using formatted values in the program and then outputting them.
* Should be used in this way: System.out.println (String.Format ("%.2f", d));
* @param D
* @return
*/
public static String FormatDouble5 (double D) {
Return String.Format ("%.2f", D);
}
public static void Main (string[] args) {
Double d = 12345.67890;
System.out.println (FormatDouble1 (d));
System.out.println (FormatDouble2 (d));
System.out.println (FormatDouble3 (d));
System.out.println (FormatDouble4 (d));
System.out.println (FormatDouble5 (d));
}
}
Java rounding holds n number