2

Currently, using DecimalFormat I would like to show maximum number of decimal places, or don't show at all. For instance,

  1. 100.0 shown as "100"
  2. 100.123 shown as "100.123"
  3. 100.123456789012345 shown as "100.123456789012345" Using format as

new DecimalFormat("0.###"); is partially correct. It works for 1st case, 2nd case but not 3rd case. As, I have no idea how much # should I have?

So, may I know what is the correct DecimalFormat I should use?

Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

1 Answers1

4

You can use setMaximumFractionDigits() to do this. The maximum value is 340, so might as well set it to that value:

public static void main(String[] args) {
    DecimalFormat formatter = new DecimalFormat();
    formatter.setMaximumFractionDigits(340);
    BigDecimal[] numbers = {new BigDecimal("100.0"), new BigDecimal("100.123"), new BigDecimal("100.123456789012345")};
    for (BigDecimal number : numbers) {         
        System.out.println(formatter.format(number));
    }
}

prints

100
100.123
100.123456789012345
Keppil
  • 45,603
  • 8
  • 97
  • 119
  • @YanChengCHEOK: Not according to the [API](http://developer.android.com/reference/java/text/DecimalFormat.html#setMaximumFractionDigits(int)). You're probably thinking of the maximum integer digits setting. – Keppil Sep 29 '12 at 15:59