[英]Best way to convert a double to String without decimal places
What is the best way to convert a double to String without decimal places?将双精度数转换为不带小数位的字符串的最佳方法是什么?
What about String.valueOf((int) documentNumber)?
String.valueOf((int) documentNumber)?
The doubles always have 0 after the decimal dot.双打在小数点后总是有 0。 I don't need to round or truncate
我不需要舍入或截断
If you are sure that the double is indeed an integer use this one:如果您确定双精度确实是一个整数,请使用这个:
NumberFormat nf = DecimalFormat.getInstance();
nf.setMaximumFractionDigits(0);
String str = nf.format(documentNumber);
As a bonus, this way you keep your locale's configuration as in thousand separator.作为奖励,通过这种方式,您可以将语言环境的配置保持为千位分隔符。
EDIT编辑
I add this previously removed option as it seems that was useful to the OP:我添加了这个以前删除的选项,因为它似乎对 OP 很有用:
Double.valueOf(documentNumber).intValue();
你可以试试这个:
String numWihoutDecimal = String.valueOf(documentNumber).split("\\.")[0];
You can convert a double to string with the minimum necessary precision:您可以将 double 转换为具有最低必要精度的字符串:
public static String ceonvert(double d)
{
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
Or this :或这个 :
> new DecimalFormat("#.##").format(2.199); //"2.2"
我不确定这是否是最好的方式,但我确信这是最短的方式:
((int)documentNumber) + ""
鉴于新编辑的问题指出双打实际上是整数,我想说您建议的答案String.valueOf((int) documentNumber)
很棒。
The easiest way to convert a double to string is to use quotation marks and then the double after that.将双精度转换为字符串的最简单方法是使用引号,然后使用双引号。 double d = 123;
双 d = 123; String a = "" + d;
字符串 a = "" + d;
Another way is to use the toString method if you want to keep the way you converted it hidden另一种方法是使用 toString 方法,如果您想隐藏转换它的方式
public String toString()
{
String a + "" d;
}
I had a similar issue where Gson converted what should have been an Integer value to a Double and I wanted to write it as a String.我有一个类似的问题,Gson 将应该是整数值转换为双精度值,我想将其写为字符串。 NumberFormat works, but you also need to disable the grouping delimiter otherwise it outputs 1,234,567:
NumberFormat 有效,但您还需要禁用分组分隔符,否则它会输出 1,234,567:
Object num = new Double(1234567);
NumberFormat nf = DecimalFormat.getIntegerInstance();
nf.setGroupingUsed(false);
String str = nf.format((Number)num);
Quotation Marks + Double引号+双引号
String s = "" + 0.07;字符串 s = "" + 0.07;
LOL this is the best way, (obviously for experienced programmers)!大声笑这是最好的方法,(显然对于有经验的程序员)!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.