0

我需要将输出四舍五入到小数点后 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
4

2 回答 2

1
System.out.printf("Sphere Surface Area is: %.4f%n", surfaceArea);
于 2013-09-11T22:38:46.290 回答
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));
}
于 2013-09-11T23:23:59.933 回答