When you need to convert string to double or float value there might be a problem with separator inside string (comma or dot). For converting your string to number you can use NumberFormatter. You just need to specify the decimal separator:
import Foundation
import UIKit
extension String {
var convertCommaToDecimal: Double {
let numberFormatter = NumberFormatter()
numberFormatter.decimalSeparator = "."
if let result = numberFormatter.number(from: self) {
return result.doubleValue
} else {
numberFormatter.decimalSeparator = ","
if let result = numberFormatter.number(from: self) {
return result.doubleValue
}
}
return 0
}
}
And the result
"3.57".convertCommaToDecimal // 3.57
"3,57".convertCommaToDecimal // 3.57
No comments:
Post a Comment