Home > Enterprise >  How to format currency number to 2 decimal places, or none if no cents?
How to format currency number to 2 decimal places, or none if no cents?

Time:09-25

I want to format a currency number to 2 decimal places if there are cents, or no decimal places if there are none.

For example, 1 would show as $1. 1.1 would show as $1.10.

Is there an easy way to do this in Android with Kotlin?

I've used DecimalFormat("$#,###,##0.##). The main issue with this is 1.1 would appear as $1.1. Tried to also use DecimalFormat($#,###,##0.#0) app crashes because it says I can't after the 0 after the # at the 12th position.

CodePudding user response:

Since Java and Kotlin work hand in hand here is a Java Solution

One way of doing this would be to check if decimal number is similar to its int or long value

if (number == (int) number)
      {
          NumberFormat formatter = new DecimalFormat ("##");
          System.out.println (formatter.format (number));
      }
else
      {
          NumberFormat formatter = new DecimalFormat ("##.00");
          System.out.println (formatter.format (number));
      }
  • Related