Home > database >  I'm trying to figure out the number formatter in macOS, I would like to only allow numbers and
I'm trying to figure out the number formatter in macOS, I would like to only allow numbers and

Time:12-01

this works great for just integer values, i found this from another stackoverflow question, but how do i set the style to allow for a decimal place as well. I'm very new to macOS, any help is appreciated!

class OnlyIntegerValueFormatter: NumberFormatter {
    
    override func isPartialStringValid(_ partialString: String, newEditingString newString: AutoreleasingUnsafeMutablePointer<NSString?>?, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
        
        // Ability to reset your field (otherwise you can't delete the content)
        // You can check if the field is empty later
        if partialString.isEmpty {
            return true
        }
        
        // Optional: limit input length
        
         if partialString.count > 8 {
         return false
         }
         
        // Actual check
        return Int(partialString) != nil
    }
}

CodePudding user response:

To allow decimal numbers, you could update your return statement to the following

// ...
    return number(from: partialString) != nil
}

Then you are allowing integer as well as decimal numbers

There are even further options available (e.g. maximumIntegerDigits) to restrict your input by using NumberFormatter (https://developer.apple.com/documentation/foundation/numberformatter)

  • Related