Java几种常见的四舍五入的方法

Python021

Java几种常见的四舍五入的方法,第1张

下面给你介绍3种常见的四舍五入:

// 方式一:BigDecimal方式

double f = 3.1315

BigDecimal b = new BigDecimal(new Double(f).toString)

double f1 = b.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue()

注意:这里一定不要直接使用new BigDecimal(double)的构造方法,而要使用new BigDecimal(new Double(1.1315).toString())的方式,不然会出现精确问题

// 方式二:DecimalFormat方式

//DecimalFormat默认采用了RoundingMode.HALF_EVEN这种类型,而且format之后的结果是一个字符串类型String

DecimalFormat df = new DecimalFormat("#.000")

System.out.println(df.format(new BigDecimal(1.0145)))//1.014

System.out.println(df.format(new BigDecimal(1.1315)))//1.132

// 方式三:

double d = 3.1415926

String result = String.format("%.2f", d)

// %.2f %. 表示 小数点前任意位数 2 表示两位小数 格式后的结果为f 表示浮点型。

java四舍五入的函数:Math.round

语法:

Math.round(x)

参数:

x 为一数值。

解释:

方法。返回对参数x四舍五入后所得的整数近似值。

例子:

public class MathTest {

public static void main(String[] args) {

System.out.println("小数点后第一位=5")

System.out.println("正数:Math.round(11.5)=" + Math.round(11.5))

System.out.println("负数:Math.round(-11.5)=" + Math.round(-11.5))

System.out.println()

System.out.println("小数点后第一位<5")

System.out.println("正数:Math.round(11.46)=" + Math.round(11.46))

System.out.println("负数:Math.round(-11.46)=" + Math.round(-11.46))

System.out.println()

System.out.println("小数点后第一位>5")

System.out.println("正数:Math.round(11.68)=" + Math.round(11.68))

System.out.println("负数:Math.round(-11.68)=" + Math.round(-11.68))

}

}

运行结果:

1、小数点后第一位=5

2、正数:Math.round(11.5)=12

3、负数:Math.round(-11.5)=-11

4、

5、小数点后第一位<5

6、正数:Math.round(11.46)=11

7、负数:Math.round(-11.46)=-11

8、

9、小数点后第一位>5

10、正数:Math.round(11.68)=12

11、负数:Math.round(-11.68)=-12