首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >静态方法的小数格式

问静态方法的小数格式
EN

Stack Overflow用户
提问于 2013-06-25 14:17:05
回答 2查看 901关注 0票数 0

编辑:这本书有一个使用柱面和使用卷的排版错误,但该程序的重点是练习使用静态方法,所以这无关紧要。

我完成了这个程序,并让它工作,以获得与我的主类交互的静态方法。我只是在小数格式上有点问题。我得到了小数点后11位的双精度。我试过使用DecimalFormat,但不管我把它放在哪里,它都没有任何影响。因为现在使用静态方法,我需要做一些额外的事情吗?

代码语言:javascript
复制
import java.text.DecimalFormat; //import DecimalFormat

class Area{

    //Area of a Circle
    static double Area(double radius){
        return Math.PI * (radius * radius);
    }

    //Area of a Rectangle
    static int Area(int width, int length){
        return width * length;
    }

    //Volume of a Cyclinder
    static double Area(double radius, double height){
        return Math.PI * (radius * radius) * height;
    }
}

public class AreaDemo{
    public static void main(String[] args){

        //Variable Declarations for each shape
        double circleRadius = 20.0;
        int rectangleLength = 10;
        int rectangleWidth = 20;
        double cylinderRadius = 10.0;
        double cylinderHeight = 15.0;

        //Print Statements for the Areas
        System.out.println("The area of a circle with a radius of " + circleRadius + " is " + Area.Area(circleRadius)); //Circle
        System.out.println("The area of a rectangle with a length of " + rectangleLength + " width of " + rectangleWidth + " is " + Area.Area(rectangleLength, rectangleWidth)); //Rectangle
        System.out.println("The area of a cylinder with radius " + cylinderRadius + " and height " + cylinderHeight + " is " + Area.Area(cylinderRadius, cylinderHeight)); //Cylinder
    }
}
EN

回答 2

Stack Overflow用户

发布于 2013-06-25 14:20:27

如果你想使用decimalFormat,你可以这样做:

代码语言:javascript
复制
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));

这将打印出1.23。如果将格式增加到"#.###,则为1.235

或者更适合你的是

代码语言:javascript
复制
DecimalFormat df = new DecimalFormat("#.##");
//Print Statements for the Areas
System.out.println("The area of a circle with a radius of " + df.format(circleRadius) + " is " + df.format(Area.Area(circleRadius))); //Circle
// do same for your others
票数 1
EN

Stack Overflow用户

发布于 2013-06-25 14:20:32

您的decimal format和Static methods之间没有关系

要控制浮点运算的精度,您应该使用java.math.BigDecimal.

或者使用Decimal Format with Pattern

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17290360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档