仅在需要时显示双精度的小数 [英] Show decimal of a double only when needed
问题描述
我用double(小数)得到了这个问题。
当double = 1.234567然后我使用 String.format(%。3f,myString);
所以结果是1.234
I got this problem with double (decimals).
When a double = 1.234567 Then I use String.format("%.3f", myString);
So the result is 1.234
但当我的双倍是10
结果将是10,000 < br>
我希望这是10
But when my double is 10
The result will be 10,000
I want this to be 10
他们是否可以说他只需要在有用时显示小数?
Is their a way to say that he only needs to show the decimals when it is "usefull"?
我看到一些关于这个的帖子,但那是php或c#,找不到关于android / java的东西(也许我看起来不太好)。
I saw some posts about this, but that was php or c#, couldn't find something for android/java about this (maybe I don't look good).
希望你们可以帮我解决这个问题。
Hope you guys can help me out with this.
编辑,现在我用的是这样的: myString.replace(,000,);
但我认为它们是一个更友好的代码。
Edit, for now I use something like this: myString.replace(",000", "");
But I think their is a more "friendly" code for this.
推荐答案
DecimalFormat 是要走的路:
public static void main(String[] args) {
double d1 = 1.234567;
double d2 = 2;
NumberFormat nf = new DecimalFormat("##.###");
System.out.println(nf.format(d1));
System.out.println(nf.format(d2));
}
将导致
1.235
2
这篇关于仅在需要时显示双精度的小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!