问题
What is the best way to convert a double to String without decimal places?
What about String.valueOf((int) documentNumber)?
The doubles always have 0 after the decimal dot. I don't need to round or truncate
回答1:
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:
Double.valueOf(documentNumber).intValue();
回答2:
You could try this:
String numWihoutDecimal = String.valueOf(documentNumber).split("\\.")[0];
回答3:
You can convert a double to string with the minimum necessary precision:
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"
回答4:
I'm not sure if this is best way, but i'am sure it's shortest way:
((int)documentNumber) + ""
回答5:
Given the newly edited question stating that the doubles are in fact integers, I'd say that your suggested answer String.valueOf((int) documentNumber)
is great.
回答6:
The easiest way to convert a double to string is to use quotation marks and then the double after that. double d = 123; String a = "" + d;
Another way is to use the toString method if you want to keep the way you converted it hidden
public String toString()
{
String a + "" d;
}
回答7:
Quotation Marks + Double
String s = "" + 0.07;
LOL this is the best way, (obviously for experienced programmers)!
来源:https://stackoverflow.com/questions/28707098/best-way-to-convert-a-double-to-string-without-decimal-places