Mode one:
Rounded
Double F = 111231.5585;
Rounding to keep two decimal digits, you can use the Format function of string,
The method is as follows:
Copy Code code as follows:
System.out.println (String.Format ("%.2f", X1));
System.out.println (String.Format ("%.2f", x2));
DecimalFormat conversion is the easiest
Copy Code code as follows:
public void m2 () {
DecimalFormat df = new DecimalFormat ("#.00");
System.out.println (Df.format (f));
}
Example: 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%. Represents a floating-point type with a result of an arbitrary number of digits before the decimal point of 2 representing a two-bit decimal format.
Mode four:
In addition, if you use the Struts tab to output, there is a Format property, set to Format= "0.00" is to keep two decimal places
For example
Copy Code code as follows:
<bean:write name= "entity" property= "Dkhafsumpl" format= "0.00"/>
The method of preserving N decimal places in Java, example.
Copy Code code as follows:
Import Java.text.DecimalFormat;
public class Numberfarmat {
public static void Main (string[] args) {
Double sd = 23.2558896635;
The first method, 10000.0, only indicates that the decimal point is reserved, and the number of digits does not matter.
Double D1 = (double) (Math.Round (sd*10000)/10000.0000000000);
Double D2 = (double) (Math.Round (sd*10000)/10000.0);
System.out.println ("4-digit decimal test:" +D1);
System.out.println ("4-digit decimal test:" +D2);
The second method
DecimalFormat DF2 = new DecimalFormat ("###.00");
DecimalFormat df3 = new DecimalFormat ("##.000");
System.out.println ("3 Decimal:" +df3.format (SD));
System.out.println ("2 decimal:" +df2.format (SD));
}
}
The results of the operation are as follows:
4-digit decimal test: 23.2559
4-digit decimal test: 23.2559
3 decimal places: 23.256
2 decimal places: 23.26