The three results of
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);
are:
3.23 0.00 2.00
java retains two decimal places:
Method 1:
Rounding
double f = 111231.5585; BigDecimal b = new BigDecimal(f); double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
retains two decimal places Decimal
Method 2:
java.text.DecimalFormat df =new java.text.DecimalFormat("#.00"); df.format(你要格式化的数字);
Example:
new java.text.DecimalFormat("#.00").format(3.1415926)
#.00 means two decimal places, #.0000 means four decimal places, and so on...
Method three:
double d = 3.1415926; String result = String .format("%.2f");
%.2f %. Represents any number of digits before the decimal point 2 Represents two decimal places The result after the format is f Represents floating point type
Method four:
NumberFormat ddf1=NumberFormat.getNumberInstance() ; void setMaximumFractionDigits(int digits)
digits The number of digits displayed
Sets the maximum number of digits displayed after the decimal point for the formatted object, and the last digit displayed is rounded
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); } }
import java.text.*; DecimalFormat df=new DecimalFormat(".##"); double d=1252.2563; String st=df.format(d); System.out.println(st);
More java enables double to retain two decimal places For related articles on the multi-method java retaining two decimal places, please pay attention to the PHP Chinese website!