3

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.

SmallGrammer
  • 893
  • 9
  • 19
  • Can you update your question to include some code of what you've tried? Have you tried using DecimalFormat? https://stackoverflow.com/questions/11826439/show-decimal-of-a-double-only-when-needed – aSemy Sep 23 '21 at 09:16
  • I've updated the post with the DecimalFormat code I've tried to use. – SmallGrammer Sep 24 '21 at 10:07
  • Here are two questions that ask the same thing (although most of the answers are unsuitable, as they'd format `1` as `1.00`) https://stackoverflow.com/q/39267621/4161471 https://stackoverflow.com/q/2379221/4161471 – aSemy Sep 24 '21 at 10:44

1 Answers1

3

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));
      }
Shivam Anand
  • 952
  • 1
  • 10
  • 21