【问题标题】:How do I get this to return a double without converting to string我如何让它返回一个双精度而不转换为字符串
【发布时间】:2016-05-20 04:35:08
【问题描述】:
public double futureInvestmentValue(int years) {
    DecimalFormat dfWithTwoDecimalPlaces;
    dfWithTwoDecimalPlaces = new DecimalFormat("0.00");
    double futureInvestmentValue = deposit * Math.pow((1 + (AnnualInterestRate / 12)), years * 12);
    return dfWithTwoDecimalPlaces.format(futureInvestmentValue);

我收到的错误与最后一行有关。它说:“类型不匹配:无法从字符串转换为双精度” 它要求我更改为公共字符串。

谢谢!

【问题讨论】:

    标签: java string return double


    【解决方案1】:

    在您的方法签名中,您将方法的返回类型声明为双精度。

    但是,这一行:

    return dfWithTwoDecimalPlaces.format(futureInvestmentValue);
    

    调用返回字符串的方法。你必须决定这个函数的用途,以及你是否需要它来返回一个预先格式化的值或把这个责任留给调用者。

    【讨论】:

    • 如何以十进制格式返回双精度。似乎每次我尝试使用 dfWithTwoDecimalPlaces.format() 时,都会出现错误。
    • double 数据类型并不像您想象的那样以十进制格式表示。 en.wikipedia.org/wiki/Double-precision_floating-point_format DecimalFormat 格式方法是一种实用方法,用于获取您在实例化它时指定的双精度值的打印格式表示。简短的回答是你不能返回十进制格式的双精度。
    • 那么这是我要在 main() 中更改以将双精度格式更改为十进制格式的内容吗?
    • @Jack Pavlov:不!你没有“改变”任何东西。 double 是 double,string 是 string - 并且(正如 Spencer Brett 正确告诉你的那样)你的方法需要传递一个或另一个。最佳方法:1)将“double”保留为 futureInvestmentValue()'s 返回值(您想要返回“数字”!),2)使用 Java Formatter(类似于您上面的内容) ,无论何时您真正想要打印该值(例如到控制台或GUI)。
    【解决方案2】:
    public double futureInvestmentValue(int years) {
        // DecimalFormat dfWithTwoDecimalPlaces; // Don't need this
        // dfWithTwoDecimalPlaces = new DecimalFormat("0.00"); // Don't need this, either
        double futureInvestmentValue = deposit * Math.pow((1 + (AnnualInterestRate / 12)), years * 12); // This is *ALL* you need!
        //return dfWithTwoDecimalPlaces.format(futureInvestmentValue); // Nope: don't return a string!
        return futureInvestmentValue; // return the double!
    

    【讨论】:

    • 如何将值作为双精度格式 (0.00) 而不是“1383.422759428736”返回这是我应该在 main() 中执行的操作吗?
    • “Double”没有HAVE“格式”。它只是一个数字,一个抽象的“值”。 “打印”——你如何表示那个值——是值本身的INDEPENDENT。在您想要的任何地方使用“格式”语句。查看herehere 以获得两种完全不同的选择。另请参阅 Javadoc:docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
    猜你喜欢
    • 2014-06-11
    • 1970-01-01
    • 2012-03-14
    • 2019-07-22
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    相关资源
    最近更新 更多