I am trying to create a method in swift that takes in a String and returns a Bool. I want to return true if the String is in a correct currency format and false if it is not.
So far this is the method I have tried:
func textIsValidCurrencyFormat(text: String) -> Bool {
var isValidCurrencyFormat = false
var numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
var number = numberFormatter.numberFromString(text)
if number != nil {
isValidCurrencyFormat = true
}
return isValidCurrencyFormat
}
PROBLEM: This works EXCEPT that I also want to invalidate strings with spaces before or after the amount and if there are more than two numbers after the decimal which this method currently accepts.
Currently I do not care if the method returns true or false based on the currency type (a.k.a. USD or GBP or some other currency) but I may want to use this to reject currencies other than a specific type in the future as well.
EDIT:
This is the final code I have come up with that correctly determines if a string is entered in a correct currency format and accounts for edge cases. Please, add any suggestions in the comments below!
func textIsValidCurrencyFormat(text: String) -> Bool {
var isValidCurrencyFormat = false
var numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
var number = numberFormatter.numberFromString(text)
if number != nil {
let numberParts = text.componentsSeparatedByString(".")
if numberParts.count == 2 {
let decimalArray = Array(numberParts[1])
if decimalArray.count <= 2 {
if text == text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) {
isValidCurrencyFormat = true
}
}
} else {
if text == text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) {
isValidCurrencyFormat = true
}
}
}
return isValidCurrencyFormat
}