Search code examples
javaformatnumber-formattingnumberformatter

Conditional NumberFormatter?


Is there a way to make a NumberFormatter that does the following:

  1. If the Double is a whole number like 5.0, display "5"

  2. If the Double is a decimal like 5.6, display "5.6"


Solution

  • double someNum = 5.6d;
    DecimalFormat df = new DecimalFormat("#.#");
    String num = df.format(someNum);
    if (num.substring(num.length - 1).equals("0")) {
        num = num.substring(0, num.length - 2);
    }
    System.out.println(num);
    

    The DecimalFormat instance formats the double into a string. The code checks the tenth place of precision, i.e. the first digit to the right of the decimal place, and if it be zero, then it shows only whole numbers. Otherwise, it shows the full precision.