Reputation: 32321
if the Value is something like this (0.0007 ) ends with 3 zeros after decimal , i am getting the result as 4.0E-4 .
Please tell me how to fix this
This is my program .
package com;
import java.text.DecimalFormat;
public class Test {
public static void main(String args[]) {
try {
String result = "";
Test test = new Test();
double value = 0.0004;
if (value < 1) {
result = test.numberFormat(value, 4);
} else {
result = test.numberFormat(value, 2);
}
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
public String numberFormat(double d, int decimals) {
if (2 == decimals)
return new DecimalFormat("#,###,###,##0.00").format(d);
else if (0 == decimals)
return new DecimalFormat("#,###,###,##0").format(d);
else if (3 == decimals)
return new DecimalFormat("#,###,###,##0.000").format(d);
else if (4 == decimals)
new DecimalFormat("#,###,###,##0.00##").format(d);
return String.valueOf(d);
}
}
Upvotes: 1
Views: 280
Reputation: 129507
How about this instead:
public static String numberFormat(double d, int decimals) {
return String.format("%." + decimals + "f", d);
}
Seems cleaner than what you're currently doing.
Upvotes: 2
Reputation: 82899
You just forgot the return statement.
else if (4 == decimals)
return new DecimalFormat("#,###,###,##0.00##").format(d);
So in the 4
case, you use DecimalFormat
to format your number, but then return just the normal string representation for the double, after the final else.
Upvotes: 6