首页 > 代码库 > JAVA保留两位小数(四舍五入)

JAVA保留两位小数(四舍五入)

 

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


public class testNumber {
	public static double num = 3.1015926;
	public static double zero = 0.00000;
	
	//方法一:打印最简便,永远是末尾有两位小数
	public static void function1(){
		 System.out.println(String.format("%.2f", num));
		 System.out.println(String.format("%.2f", zero));
	}
	
	//方法二:转换后是String类型
	public static void function2(){
		DecimalFormat df = new DecimalFormat("0.00");
		System.out.println(df.format(num));
		System.out.println(df.format(zero));
	}
	
	//方法三:转换后是double类型,但会省去最末位的0,只保留一位0
	public static void function3(){
		BigDecimal bg1 = new BigDecimal(num);
		double finalNum = bg1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		System.out.println(finalNum);
		
		BigDecimal bg2 = new BigDecimal(zero);
		double finalZero = bg2.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		System.out.println(finalZero);
	}
		
	//方法四:末尾的0都会省去 3.1001->3.1,0.0000->0
	public static void function4(){
		NumberFormat nf = NumberFormat.getNumberInstance();
		nf.setMaximumFractionDigits(2);
		System.out.println(nf.format(num));
		System.out.println(nf.format(zero));
	}
	
	public static void main(String args[]){
		System.out.println("function1:");
		function1();
		System.out.println("function2:");
		function2();
		System.out.println("function3:");
		function3();
		System.out.println("function4:");
		function4();
	}
}

 

结果展示:

技术分享


 

JAVA保留两位小数(四舍五入)