Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 537
SmallGrammer Avatar asked Sep 02 '25 15:09

SmallGrammer


1 Answers

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));
      }
like image 141
Shivam Anand Avatar answered Sep 05 '25 05:09

Shivam Anand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!