java保留小数

java学习中遇到的问题(1)

java中保留几位小数的办法

1 使用printf()

int n = 1.234
System.out.printf("%.2f",n);

得出的结果显然就是n = 1.23

2 使用java中的DecimalFormat类

下面是一个例子

import java.text.DecimalFormat;
import java.util.Scanner;

public class network3 {
    public static void main(String[] args){
        Scanner s = new Scanner(System.in);
        int a = s.nextInt();
        int b = s.nextInt();
        int c = s.nextInt();
        int d = s.nextInt();
        int Sum = a+b+c+d;
        double Average = (a+b+c+d)/4.0;
        DecimalFormat df = new DecimalFormat("#.0");
        System.out.print("Sum="+Sum+";Average="+df.format(Average));
        /*我爱岩宝宝*/
    }
}

结果是average可以取得两位小数
DecimalFormat可以用科学记数法来格式化数字
例如使用0.###E0 将2E345格式化为2.345E3

猜你喜欢

转载自blog.csdn.net/m0_37160376/article/details/80257194