There are four common methods to retain decimal places in java: rounding, DecimalFormat, format, String. format, and struts label operation implementation.
Method 1:
Rounding
Double f = 111231.5585;
Returns two decimal places. The String format function can be used,
The method is as follows:
| The Code is as follows: |
Copy code |
|
System. out. println (String. format ("%. 2f", x1 ));
System. out. println (String. format ("%. 2f", x2 )); |
The easiest way to convert DecimalFormat
| The Code is as follows: |
Copy code |
Public void m2 (){
DecimalFormat df = new DecimalFormat ("#. 00 ");
System. out. println (df. format (f ));
} |
Example: new java. text. DecimalFormat ("#. 00"). format (3.1415926)
#. 00 indicates two decimal places #. 0000 four decimal places, and so on...
Method 3:
| The Code is as follows: |
Copy code |
|
Double d = 3.1415926;
String result = String. format ("%. 2f "); |
%. 2f %. indicates any number of digits before the decimal point. 2 indicates the result of two decimal places. f indicates the floating point type.
Method 4:
In addition, if the struts label is used for output, there is a format attribute, set to format = "0.00" is to keep two decimal places
For example
| The Code is as follows: |
Copy code |
| : <Bean: write name = "entity" property = "dkhAFSumPl" format = "0.00" type = "codeph" text = "/codeph"/> |
JAVA to retain N decimal places, for example.
| The Code is as follows: |
Copy code |
Import java. text. DecimalFormat;
Public class numberFarmat {
Public static void main (String [] args ){
Double sd = 23.2558896635;
// The first method is 10000.0. after the decimal point, only the decimal points are retained, which has nothing to do with the number of digits.
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 );
// Method 2
DecimalFormat df2 = new DecimalFormat ("###. 00 ");
DecimalFormat df3 = new DecimalFormat ("#. 000 ");
System. out. println ("3 decimal places:" + df3.format (sd ));
System. out. println ("2 decimal places:" + df2.format (sd ));
}
}
|
The running result is as follows:
4-digit decimal test: 23.2559
4-digit decimal test: 23.2559
3 decimal places: 23.256
2 decimal places: 23.26