Is there a way to make a NumberFormatter that does the following:
If the Double is a whole number like 5.0, display "5"
If the Double is a decimal like 5.6, display "5.6"
Is there a way to make a NumberFormatter that does the following:
If the Double is a whole number like 5.0, display "5"
If the Double is a decimal like 5.6, display "5.6"
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)")
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.