Hi, Is there a way to format a decimal as following:
100 -> "100" 100.1 -> "100.10"
i.e. if it is round omit the decimal part otherwise always show 2dp.
Thxs.
Hi, Is there a way to format a decimal as following:
100 -> "100" 100.1 -> "100.10"
i.e. if it is round omit the decimal part otherwise always show 2dp.
Thxs.
Yes. You can use java.util.formatter. You can use a formatting string like "%10.2f"
you should do something like this:
public static void main(String[] args) {
double d1 = 100d;
double d2 = 100.1d;
print(d1);
print(d2);
}
private static void print(double d) {
String s = null;
if (Math.round(d) != d) {
s = String.format("%.2f", d);
} else {
s = String.format("%.0f", d);
}
System.out.println(s);
}
which prints:
100
100,10
I doubt it. The problem is that 100 is never 100 if it's a float, it's normally 99.9999999999 or 100.0000001 or something like that.
If you do want to format it that way, you have to define an epsilon, that is, a maximum distance from an integer number, and use integer formatting if the difference is smaller, and a float otherwise.
Something like this would do the trick:
public String formatDecimal(float number) {
float epsilon = 0.004; // 4 tenths of a cent
if ( abs(Math.round(number) - number) < epsilon) {
return String.format("%10.0f", number); // sdb
} else {
return String.format("%10.2f", number); // dj_segfault
}
}
I'd recommend using the java.text package:
double money = 100.1;
NumberFormat formatter = NumberFormat.getCurrencyInstance();
System.out.println(formatter.format(money));
This has the added benefit of being locale specific.