Skip to content
Advertisement

How to format decimals in a currency format?

Is there a way to format a decimal as following:

100   -> "100"  
100.1 -> "100.10"

If it is a round number, omit the decimal part. Otherwise format with two decimal places.

Advertisement

Answer

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.004f; // 4 tenths of a cent
  if (Math.abs(Math.round(number) - number) < epsilon) {
     return String.format("%10.0f", number); // sdb
  } else {
     return String.format("%10.2f", number); // dj_segfault
  }
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement