Reputation: 291
I want to convert double to string. If I use Double.toString or String.valueOf it gives someting awful like 5e-10 or something like that.
if i have x = 0.00000032 i want to have string "0.00000032", simply.
I did it in a long way and I want to know whether there is a better (shorter) way to do it.
szText += String.format("%.20f", dOutput);
iZeros = 0;
for(int i=szText.length() - 1; i>=0; i--)
{
if(szText.charAt(i) == '0')
++iZeros;
else break;
}
szText = szText.substring(0, szText.length() - iZeros);
Upvotes: 0
Views: 167
Reputation: 1
BigDecimal.valueOf(value).setScale(decimalLimit, RoundingMode.HALF_UP).toPlainString()
Upvotes: 0
Reputation: 14019
This is the prime use case for the DecimalFormat class.
You'll want something along the lines of
DecimalFormat formatter = new DecimalFormat("#.#");
String output = formatter.format(input);
The default behaviour of DecimalFormat
is to round the fraction part to one decimal place. To change that, use MadProgrammer's solution of setting formatter.setMaximumFractionDigits(100)
or something like that.
Upvotes: 1
Reputation: 347332
There's probably better choices, but you could use something like...
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(100);
double x = 0.00000032d;
System.out.println(x);
System.out.println(nf.format(x));
Which outputs
3.2E-7
0.00000032
You might want to play around with the maximumFractionDigits
property to you specific needs...
Upvotes: 5