Java中保留指定小数位数

版权声明:本文为博主原创文章,如果喜欢欢迎收藏转载! https://blog.csdn.net/houwanle/article/details/83927738

方式一:

import java.math.BigDecimal;

/*
 * 计算并输出1/3.0的值,保留小数点后2位
 * 方式一:四舍五入
 */
public class Main{
	public static void main(String[] args){
		double n = 1/3.0;
		BigDecimal b = new BigDecimal(n);
		double m = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		System.out.println(m);
	}
}

输出结果:0.33

方式二:

import java.text.DecimalFormat;

/*
 * 计算并输出1/3.0的值,保留小数点后2位
 * 方式二:
 */
public class Main {
	public static void main(String[] args){
		//#.00 表示两位小数 #.0000四位小数 以此类推…
		DecimalFormat df = new DecimalFormat("0.00");
		System.out.println(df.format(1/3.0));
	}
}

输出结果:0.33

方式三:

/*
 * 计算并输出1/3.0的值,保留小数点后2位
 * 方式三:
 */
public class Main {
	public static void main(String[] args){
		double n = 1/3.0;
		//%.2f: %. 表示 小数点前任意位数;  2 表示两位小数; 格式后的结果为f 表示浮点型。
		String res  = String.format("%.2f", n);
		System.out.println(res);
	}
}

输出结果:0.33

猜你喜欢

转载自blog.csdn.net/houwanle/article/details/83927738