Reputation: 5204
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
Upvotes: 12
Views: 50101
Reputation: 1
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. NumberFormat works, but you also need to disable the grouping delimiter otherwise it outputs 1,234,567:
Object num = new Double(1234567);
NumberFormat nf = DecimalFormat.getIntegerInstance();
nf.setGroupingUsed(false);
String str = nf.format((Number)num);
Upvotes: 0
Reputation: 55
Quotation Marks + Double
String s = "" + 0.07;
LOL this is the best way, (obviously for experienced programmers)!
Upvotes: -3
Reputation: 34
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;
}
Upvotes: 0
Reputation: 15875
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.
Upvotes: 0
Reputation: 4065
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();
Upvotes: 16
Reputation: 503
I'm not sure if this is best way, but i'am sure it's shortest way:
((int)documentNumber) + ""
Upvotes: 1
Reputation: 71
You could try this:
String numWihoutDecimal = String.valueOf(documentNumber).split("\\.")[0];
Upvotes: 7
Reputation: 713
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"
Upvotes: 4