Copy Code code as follows:
Mport Java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat ("##### #0.00");
Double D1 = 3.23456
Double d2 = 0.0;
Double d3 = 2.0;
Df.format (D1);
Df.format (D2);
Df.format (D3);
The 3 results were:
Copy Code code as follows:
Java preserves two-bit decimal problems:
Mode one:
Rounded
Copy Code code as follows:
Double F = 111231.5585;
BigDecimal B = new BigDecimal (f);
Double f1 = B.setscale (2, bigdecimal.round_half_up). Doublevalue ();
Keep two decimal digits
Mode two:
Copy Code code as follows:
Java.text.DecimalFormat DF =new Java.text.DecimalFormat ("#.00");
Df.format (the number you want to format);
Cases:
Copy Code code as follows:
New Java.text.DecimalFormat ("#.00"). Format (3.1415926)
#.00 represents a two-bit decimal #.0000 four-bit decimal, and so on ...
Mode three:
Copy Code code as follows:
Double d = 3.1415926;
string result = string. Format ("%.2f");
%.2f%. Indicates that the result of an arbitrary number of digits before the decimal point 2 represents a two-bit decimal format is a floating-point type
Mode four:
Copy Code code as follows:
NumberFormat ddf1=numberformat.getnumberinstance ();
void setmaximumfractiondigits (int digits)
Number of digits displayed by digits
Sets the maximum number of digits to display after the decimal point is set for the formatted object, and the last bit displayed is rounded
Copy Code code as follows:
Import java.text.*;
Import java.math.*;
Class TT
{
public static void Main (String args[])
{Double x=23.5455;
NumberFormat ddf1=numberformat.getnumberinstance ();
Ddf1.setmaximumfractiondigits (2);
String s= Ddf1.format (x);
System.out.print (s);
}
}
Copy Code code as follows:
Import java.text.*;
DecimalFormat df=new DecimalFormat (". # #");
Double d=1252.2563;
String St=df.format (d);
System.out.println (ST);