I'm formatting a String
from a UITextField
with input type number :
Example : If I have '10000', I format '10000' to have '10 000' String
.
Problem : Later I need access to the Int value of this String, but when casting, I got an exception because the String
is not well formatted to be casted as it contains spaces. (Example : Int("10 000") not working.)
So I want to remove spaces from the String
before casting to Int
, by using : myString.trimmingCharacters(in: .whitespaces)
but the spaces are still here.
I'm using the following extension :
extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.groupingSeparator = " "
formatter.numberStyle = .decimal
return formatter
}()
}
extension BinaryInteger {
var formattedWithSeparator: String {
return Formatter.withSeparator.string(for: self) ?? ""
}
}
I also tried to retrieve the original NSNumber
from my Formatter by doing :
print(Formatter.withSeparator.number(from: "10 000").intValue)
But result is nil
too.
Any idea ?