英文:
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("#.0");
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论