java 倍数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16515732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 23:11:59  来源:igfitidea点击:

Double to Number

javadoubletype-conversiontype-mismatch

提问by ajjukhot

How to convert Double to Number in Java, like in the code below?

如何在 Java 中将 Double 转换为 Number,如下面的代码所示?

public Number parse(String text, ParsePosition status) {
    // find the best number (defined as the one with the longest parse)
    int start = status.index;
    int furthest = start;
    double bestNumber = Double.NaN;
    double tempNumber = 0.0;
    for (int i = 0; i < choiceFormats.length; ++i) {
        String tempString = choiceFormats[i];
        if (Misc.regionMatches(start, tempString, 0, tempString.length(), text)) {
            status.index = start + tempString.length();
            tempNumber = choiceLimits[i];
            if (status.index > furthest) {
                furthest = status.index;
                bestNumber = tempNumber;
                if (furthest == text.length()) break;
            }
        }
    }
    status.index = furthest;
    if (status.index == start) {
        status.errorIndex = furthest;
    }
    int c= 0;
    return new Double(bestNumber); 
}

But in Eclipse it shows

但在 Eclipse 中它显示

Type mismatch: cannot convert from Double to Number

Actually this code belongs to ChoiceFormat.javaclass from java.textpackage.

实际上这段代码属于包中的ChoiceFormat.javajava.text

回答by NINCOMPOOP

java.lang.Doubleis a subclass of java.lang.Number. Hence the posted code shouldn't show any compilation error if you are returning a java.lang.Doublefrom a method which returns java.lang.Number.

java.lang.Double的是子类java.lang.Number中。因此,如果您java.lang.Double从返回java.lang.Number.

As Jon Skeet pointed out, "you've got a different Double type or a different Number type somewhere". Please double check to see if you are using java.lang.Doubleand java.lang.Number.

正如 Jon Skeet 指出的那样,“您在某处拥有不同的 Double 类型或不同的 Number 类型”。请仔细检查您是否正在使用java.lang.Doublejava.lang.Number

回答by Sanjaya Liyanage

Use casting

使用铸造

Double d=new Double(2);
Number n=(Number)d;

in your case

在你的情况下

Double d=new Double(bestNumber);
Number n=(Number)d;

return n;