0

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"

KaliMa
  • 1,970
  • 6
  • 26
  • 51
  • 1
    The answer is absolutely yes. You can write your own subclass of `NumberFormatter` to do whatever you like. – Dawood ibn Kareem Jan 15 '17 at 03:37
  • I had tried solutions from http://stackoverflow.com/questions/41657200/how-to-default-an-edittext-to-integer-but-allow-decimal-input/41657315 but nothing is working so I am trying a format solution – KaliMa Jan 15 '17 at 03:37
  • @DavidWallace I'm sure it can be done, but if I knew how to do it in this case I wouldn't have asked – KaliMa Jan 15 '17 at 03:39
  • By the way, do you mean the Swing `NumberFormatter` class, or do you actually mean `NumberFormat`? – Dawood ibn Kareem Jan 15 '17 at 03:39
  • I don't know the difference; whatever will work – KaliMa Jan 15 '17 at 03:40
  • Then your question is unclear. Are you looking for a `NumberFormatter` or a `NumberFormat`? If you don't say what you're going to _do_ with it, then how can anyone tell you which one will actually "work"? – Dawood ibn Kareem Jan 15 '17 at 03:52
  • Possible duplicate of [How to nicely format floating numbers to String without unnecessary decimal 0?](http://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0) – David Rawson Jan 15 '17 at 04:10

2 Answers2

0

I know this is an old question but this should do exactly what you asked:

    var myNumber:Double = 0.0  // set to 5.0 or 5.6 to see result

    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 4
    let x = formatter.string(from: NSNumber(value: myNumber)) ?? "$\(myNumber)"
    print("x = \(x)")
Greg
  • 667
  • 8
  • 19
-1
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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360