Example 1
Float f = 34.237323f;
BigDecimal B = new BigDecimal (f );
Float f1 = B. setScale (2, BigDecimal. ROUND_HALF_UP). floatValue ();
System. out. println (f1 );
Method 2:
Float f = 34.232323;
BigDecimal B = new BigDecimal (f );
Float f1 = B. setScale (2, BigDecimal. ROUND_HALF_UP). floatValue ();
// B. setScale (2, BigDecimal. ROUND_HALF_UP) indicates rounding and retaining two decimal places
Method 3:
Float size = 34.236323;
DecimalFormat fnum = new DecimalFormat ("#0.00 ");
String dd = fnum. format (scale );
System. out. println (dd );
Method 4:
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 5:
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
Example: <bean: write name = "entity" property = "dkhAFSumPl" format = "0.00"/>
Method 6:
Public static void main (String [] args ){
// 1. First multiply, then round, and then divide;
Double d = 62.31060027198647;
Double d2 = Math. round (d * 100)/100.0;
System. out. println ("use Math to perform division:" + d2 );
// 2. Use setScale () of BigDecimal to realize rounding and determining the number of decimal places, and convert it into a BigDecimal object.
BigDecimal bd = new BigDecimal (d );
BigDecimal bd2 = bd. setScale (2, BigDecimal. ROUND_HALF_UP );
System. out. println ("obtained through BigDecimal. setScale:" + bd2 );
// 3. Return the String's
DecimalFormat df = new DecimalFormat ("#.##");
System. out. println ("obtained through DecimalFormat. format:" + df. format (d ));
// 4. Use String. format
System. out. println ("via StringFormat:" + String. format ("%. 2f", d ));
}
// Use Math to perform the division: 62.31
// Get: 62.31 through BigDecimal. setScale
// Use DecimalFormat. format to obtain: 62.31
// Use StringFormat: 62.31