如何获得4位小数的输出答案

时间:2013-09-11 22:35:11

标签: java

我需要将输出四舍五入到小数点后4位但是我不太清楚如何做到这一点我的东西运行的确切如何我也想要它也需要将最后一个小数点四舍五入

import java.util.Scanner;  //Needed for the Scanner class  

public class SphereCalculations
{    
public static void main(String[] args)  //all the action happens here!    
{   Scanner input = new Scanner (System.in);

    double radius;
    double volume;
    double surfaceArea;

    System.out.println("Welcome to the Sphere Calculator. ");
    System.out.print( "Enter radius of sphere: " );
    radius = input.nextDouble();


    volume = ((4.0 / 3.0) * (Math.PI * Math.pow(radius, 3)));
    surfaceArea = 4 * (Math.PI * Math.pow(radius, 2));


    System.out.println("The Results are: ");
    System.out.println("Radius: " + radius);
    System.out.println("Sphere volume is: " + volume);
    System.out.println("Sphere Surface Area is: " + surfaceArea);
}
}

输出:

Radius: 7.5
Volume: 1767.1459
Surface Area: 706.8583

2 个答案:

答案 0 :(得分:1)

System.out.printf("Sphere Surface Area is: %.4f%n", surfaceArea);

答案 1 :(得分:0)

如果您发现需要更多控制权,可以使用DecimalFormat,其中包含更多格式选项。如果您想用科学记数法打印双精度版,这将特别有用。

//specify a number locale, some countries use other symbols for the decimal mark
NumberFormat f = NumberFormat.getInstance(Locale.ENGLISH);
if(f instanceof DecimalFormat) {
    DecimalFormat d = (DecimalFormat) f;
    d.applyPattern("#.0000"); //zeros are non optional, use # instead if you don't want that
    System.out.println(d.format(surfaceArea));
}