Java中精确到小数点后n位

959 阅读2分钟

由于做上机题时需要读取输入并输出结果,题目要求输出小数点后指定位数结果,于是在此总结

方法一:使用DecimalFormat类

  1. 导入java.text.DecimalFormat类import java.text.DecimalFormat;
  2. 然后创建一个DecimalFormat类的对象,其中参数的格式为“#.0”后面加上想要精确的小数位数,比如精确到小数点后两位就是“#.00”: DecimalFormat df = new DecimalFormat("#.00");
  3. 最后使用该对象的format()方法将需要精确的数字作为参数传入,即可得到精确到小数点后c位的字符串:
    double num = 1.234567; 
    String result = df.format(num); 
    // result的值为"1.23"
    

该方法不太适合传入一个参数,指定为精确的n位。

方法二:格式化输出

学过C语言的同学都知道这中输出方法在C中很常用,其实在Java中,这种方法也可以使用。例如像下面这样可以指定小数点后2位

double a = 1.234567;
System.out.printf("%.2f\n",a);
 // 打印结果为"1.23"

而如果想指定n位小数可以使用如下方法

double a = 1.234567;
int n = 3;
String s = "%." + n + "f\n";
System.out.printf(s, a);
// 打印结果为"1.235",因为会四舍五入

方法三:使用 BigDecimal 类

  1. 首先导入java.math.BigDecimal类: import java.math.BigDecimal;
  2. 创建一个BigDecimal类的对象,将需要精确的数字作为参数传入: BigDecimal num = new BigDecimal("1.234567");
  3. 然后使用setScale()方法将小数位数设置为需要的值,该方法接受两个参数,第一个参数为小数点后保留的位数,第二个参数为舍入模式,常用的有四种模式:
    • RoundingMode.UP:向上舍入
    • RoundingMode.DOWN:向下舍入
    • RoundingMode.CEILING:向正无穷舍入
    • RoundingMode.FLOOR:向负无穷舍入
      例如,要将数字精确到小数点后两位,可以使用如下代码: num = num.setScale(2, RoundingMode.HALF_UP); 如果要进行截断n位,而不是四舍五入,可以使用如下代码:num = num.setScale(2, RoundingMode.FLOOR);
  4. 最后使用toString()方法将 BigDecimal 对象转换为字符串即可: String result = num.toString(); // result的值为"1.23"

输入正整数 a,b,c,输出 a/b 的小数形式,精确到小数点后 c 位。解题代码如下

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;

public class Main{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()){
            String[] strings = sc.nextLine().split(" ");
            int a = Integer.parseInt(strings[0]);
            int b = Integer.parseInt(strings[1]);
            int c = Integer.parseInt(strings[2]);
            if(a == 0 && b==0 && c==0){
                return;
            }
            double res = 1.0 * a / b;
            BigDecimal num = new BigDecimal(Double.toString(res));
            // 需要截尾处理,而不是四舍五入
            num = num.setScale(c, RoundingMode.FLOOR);
            System.out.println(num);
        }
    }
}