java保留小数的四种方式

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;


public class FormatNumber {
	//BigDecimal
	public static void format1(String sf){
		BigDecimal b = new BigDecimal(sf);
		double d = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		System.out.println(d);
	}
	//String.format()
	public static void format2(String sf){
		Double d = new Double(sf);
		System.out.println(String.format("%.2f", d));
	}
	//DecimalFormat
	public static void format3(String sf){
		Double d = new Double(sf);
		DecimalFormat df = new DecimalFormat("#.00");
		sf = df.format(d);
		System.out.println(sf);
	}
	//NumberFormat
	public static void format4(String sf){
		Double d = new Double(sf);
		NumberFormat nf = NumberFormat.getNumberInstance();
		nf.setMaximumFractionDigits(2);
		sf = nf.format(d);
		System.out.println(sf);
	}
	
	public static void main(String[] args){
		String sf = "123456.3000";
		format1(sf);
		format2(sf);
		format3(sf);
		format4(sf);
	}
}

结果为: BigDecimal方式: 123456.3 

       String.format()方式: 123456.30

       DecimalFormat方式: 123456.30 

       NumberFormat方式: 123,456.3

你可能感兴趣的:(java,保留小数)