Update
In case you need to format 1345.999
as 1346
(as mentioned in your comment), you can do so by adding a couple of extra steps in the original answer:
- Format the number with the pattern,
#,###,###.00
and then remove all commas so that it can be parsed back to double.
- Parse the converted string into
double
and follow the rest of the solution as mentioned in the original answer.
Demo:
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Main {
public static void main(String[] args) {
System.out.println(getFromattedNumber(1234567.0));
System.out.println(getFromattedNumber(1234567.20));
System.out.println(getFromattedNumber(1234567.01));
System.out.println(getFromattedNumber(1234567.00));
System.out.println(getFromattedNumber(1345.999));
}
static String getFromattedNumber(double number) {
NumberFormat format = new DecimalFormat("#,###,###.00");
double num = Double.parseDouble(format.format(number).replace(",", ""));
// Format for integer decimal numbers
NumberFormat formatInt = new DecimalFormat("#,###,###");
if ((int) num == num) {
return formatInt.format(number);
} else {
return format.format(number);
}
}
}
Output:
1,234,567
1,234,567.20
1,234,567.01
1,234,567
1,346
Original answer
You will need to use two formats as shown below:
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class Main {
public static void main(String[] args) {
System.out.println(getFromattedNumber(1234567.0));
System.out.println(getFromattedNumber(1234567.20));
System.out.println(getFromattedNumber(1234567.01));
System.out.println(getFromattedNumber(1234567.00));
}
static String getFromattedNumber(double number) {
// Format for integer decimal numbers
NumberFormat format1 = new DecimalFormat("#,###,###");
// Format for non-integer decimal numbers
NumberFormat format2 = new DecimalFormat("#,###,###.00");
if ((int) number == number) {
return format1.format(number);
} else {
return format2.format(number);
}
}
}
Output:
1,234,567
1,234,567.20
1,234,567.01
1,234,567