Search code examples
swiftxcodeios11computed-properties

Removing the decimal part of a double without converting it to Int in swift


Im a making a calculator App in ios and I have a computed property as shown below . I want to display for example let the display value be a whole number say 3.0 I want it to be displayed as just 3 and when the display value is not a whole number like this 3.4 then it should remain same . display.text is the label that is used to display the value of the calculator App I have a code block like this :

 private var displayValue : Double {
            get {
               return Double(display.text!)!
            }
            set {
                display.text = String(newValue)
            }
        }

Solution

  • I recommend NumberFormatter, this example creates a reusable formatter.

    let decimalFormatter : NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter
    }()
    

    private var displayValue : Double {
        get {
            return Double(display.text!)!
        }
        set {
            display.text = decimalFormatter.string(for: newValue)
        }
    }