DecimalFormat and NumberFormat should work just fine. A currency instance could work even better:
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Foo {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("#0.00");
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
NumberFormat cf = NumberFormat.getCurrencyInstance();
System.out.printf("0 with df is: %s%n", df.format(0));
System.out.printf("0 with nf is: %s%n", nf.format(0));
System.out.printf("0 with cf is: %s%n", cf.format(0));
System.out.println();
System.out.printf("12345678.3843 with df is: %s%n",
df.format(12345678.3843));
System.out.printf("12345678.3843 with nf is: %s%n",
nf.format(12345678.3843));
System.out.printf("12345678.3843 with cf is: %s%n",
cf.format(12345678.3843));
}
}
This would output:
0 with df is: 0.00
0 with nf is: 0.00
0 with cf is: $0.00
12345678.3843 with df is: 12345678.38
12345678.3843 with nf is: 12,345,678.38
12345678.3843 with cf is: $12,345,678.38
Double.valueOf
. Just a guess, though. – Milliganm_interest
using theDecimalFormat
before printing it? Because I can see you doingDouble.valueOf()
on the final result and if you're going to print that as such, then you're bound to get varying decimal points. – Vulnerable