0

每当从 calculateVolume() 返回一个双精度值时,它都会获得一个值,例如 1.0,这需要显示为 1.00(2 个小数而不是 1)。这可能很容易,但我没有看到我现在做错了什么。有人可以帮我做一个简短的解释。非常感谢!

public class Block extends Shape {
private double length;
private double width;
private double height;


public Block(double length, double width, double height){
    this.length = length;
    this.width = width;
    this.height = height;

}

@Override
public double calculateVolume(){ 

    return Math.round((length * width * height)* 100.0) / 100.0;
}
4

3 回答 3

1

你有两种选择来解决这个问题:

1.查看DecimalFormat文档了解更多详细信息。

    DecimalFormat df = new DecimalFormat("#.##");
    System.out.print(df.format(calculateVolume()));

2.另一个选项是这个:格式化数字打印

System.out.printf("%.2f", calculateVolume());

希望能帮助到你。

于 2013-09-19T18:26:22.110 回答
1

使用DecimalFormat该类(并确保您查看该文档!)格式化您的数字以进行输出。您还可以使用标准String格式选项来满足不太复杂的要求(但我更喜欢DecimalFormat)。

DecimalFormat fmt = new DecimalFormat("#.##"); // Two decimal places
System.out.print(fmt.format(calculateVolume()));
于 2013-09-19T18:27:42.647 回答
0
System.out.printf("%.2f", yourVariable);

您还可以在http://docs.oracle.com/javase/tutorial/java/data/numberformat.html找到不同的格式化方法

于 2013-09-19T18:28:44.157 回答