double保留两位小数,四种方法
package com.math;
import java.text.DecimalFormat;
import java.text.NumberFormat;
/**
* Double保留两位小数,四舍五入
* @author luolei
* @date 2019年2月13日
*/
public class DoubleFormat {
public static void main(String[] args) {
// TODO Auto-generated method stub
double d = 520.1314520; //520.13
//double d = 520.1314; //520.13
//double d = 520.1394; //520.14
//double d = 520; //520.0
//double d = 520.0; //520.0
//double d = 520.00; //520.0
//1、
DecimalFormat df = new DecimalFormat("#.00");
System.out.println(Double.parseDouble(df.format(d)));
//2、
System.out.println(Double.parseDouble(String.format("%.2f", d)));
//3、
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
String dStr = nf.format(d);
System.out.println(Double.parseDouble(dStr));
//4、
double dd = (double)Math.round(d*100)/100;
System.out.println(dd);
}
}