# 如何在 Java 中把双精度数四舍五入到小数点后两位数

## 使用 `Math.round(double*100.0)/100.0` 将一个双精度数四舍五入到小数点后两位

``````import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
public static void main(String[] args)
{
double d = 7435.9876;
double roundDbl = Math.round(d*100.0)/100.0;
System.out.println("Rounded Double value: "+roundDbl);
}
}
``````

``````Rounded Double value: 7435.99
``````

## 使用 `BigDecimal` 将一个双精度数舍入到两个小数位上

``````import java.util.*;
import java.lang.*;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Main
{
public static void main(String[] args)
{
double val1 = 4312.186462;
System.out.println("Double value: "+val1);

BigDecimal bd = new BigDecimal(val1).setScale(2, RoundingMode.HALF_UP);
double val2 = bd.doubleValue();
System.out.println("Rounded Double value: "+val2);
}
}
``````

``````Double value: 4312.186462
Rounded Double value: 4312.19
``````

## 使用 `DecimalFormat` 将一个双精度数四舍五入到小数点后两位

``````import java.util.*;
import java.lang.*;
import java.io.*;
import java.text.DecimalFormat;

public class Main
{
public static void main(String[] args)
{
double val1 = 6482.236789;
System.out.println("Double value: "+val1);

DecimalFormat df = new DecimalFormat("###.##");
System.out.println("Rounded Double value (DecimalFormat): "+df.format(val1));
}
}
``````

``````Double value: 6482.236789
Rounded Double value: 6482.24
``````

## 使用 `Apache Common` Math 将一个双精度数值四舍五入到两位小数

``````<dependency>
<groudId>org.apache.commons</groudId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
``````

``````import java.util.*;
import java.lang.*;
import java.io.*;
import org.apache.commons.math3.util.Precision;

public class Main
{
public static void main(String[] args)
{
double input = 9476.2351;
double roundedDbl = Precision.round(input,2);
System.out.println("Rounded Double value: "+roundedDbl);
}
}
``````

``````Rounded Double value: 9476.24
``````

## 相关文章 - Java Double

• 如何在 Java 中把字符串转换为双数