1

I have a string that I would like to be formatted such that when it is not a whole number, it will display up to two decimal places but if it is a whole number, there should be no decimal places.

Is there an easier way to do this in swift or do I have to settle for an if-else?

dypbrg
  • 725
  • 1
  • 6
  • 16

1 Answers1

2

You can extend FloatingPoint to check if it is a whole number and use a condition to set the minimumFractionDigits property of the NumberFormatter to 0 in case it is true otherwise set it to 2:

extension Formatter {
    static let custom: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.maximumFractionDigits = 2
        return formatter
    }()
}
extension FloatingPoint {
    var isWholeNumber: Bool { isNormal ? self == rounded() : isZero }
    var custom: String {
        Formatter.custom.minimumFractionDigits = isWholeNumber ? 0 : 2
        return Formatter.custom.string(for: self) ?? ""
    }
}

Playground testing:

1.0.custom    // "1"
1.5.custom    // "1.50"
1.75.custom   // "1.75"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 1
    I have never seen that question and it is already closed. Btw none of them uses the approach I showed here. – Leo Dabus Jan 19 '18 at 05:35
  • yes your solution might a better than other's so you can answer old questions as a better solution. as old question been searched the most then newer so this would be more helpful :) – Prashant Tukadiya Jan 19 '18 at 05:37
  • Appreciate the answer, I don't think it's a duplicate since I was actually asking if there's a shorter way of doing it than having to do any calculations for it – dypbrg Jan 27 '18 at 06:56