整数转换为带有一位小数的双精度数(Java)

huangapple go评论73阅读模式
英文:

Whole numbers to doubles with one decimal number in java

问题

我正在使用DecimalFormat将我的数字四舍五入到一位小数。然而,像20这样的数字显示为20,而不是显示为20.0

所以我的代码是这样的:

int myWholeNumber = 20;
DecimalFormat df = new DecimalFormat("#.#");
double toDouble = Double.parseDouble(df.format(myWholeNumber));
System.out.println(toDouble);

但输出与期望的不同:

输出

20

期望

20.0
英文:

I'm using DecimalFormat to round my numbers to exactly with one decimal. However, numbers like 20 don't show up as 20.0 and it just shows 20.

So my code is like this:

int myWholeNumber = 20;
DecimalFormat df = new DecimalFormat("#.#");
double toDouble = Double.parseDouble(df.format(myWholeNumber));
System.out.println(toDouble);

but the output differs from the wanted one:

Output

20

Wanted

20.0

答案1

得分: 4

明确在你的格式字符串中包含一个零

import java.text.DecimalFormat;

public class Main {

    public static void main(String[] args) {
        int myWholeNumber = 20;
        DecimalFormat df = new DecimalFormat("#.0");
        double myDoubleNumber = Double.valueOf(myWholeNumber);
        System.out.println(df.format(myDoubleNumber));
    }

}

输出:

20.0

在这里尝试一下:链接


<details>
<summary>英文:</summary>

Explicitly have a zero in your format string:

    import java.text.DecimalFormat;
    
    public class Main {
    
        public static void main(String[] args) {
            int myWholeNumber = 20;
            DecimalFormat df = new DecimalFormat(&quot;#.0&quot;);
            double myDoubleNumber = Double.valueOf(myWholeNumber);
            System.out.println(df.format(myDoubleNumber));
        }
    
    }

**Output:**

    20.0

Try it out [here][1].


  [1]: https://repl.it/repls/LeafyElaborateAngles

</details>



huangapple
  • 本文由 发表于 2020年10月21日 21:23:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/64464493.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定