In a string with just numbers and commas how do I convert that into a double

579 Views Asked by At

So I have a string with just numbers and commas. for example "1,233,323.32"(String) but I want to convert that to 1233323.32(double).

3

There are 3 best solutions below

0
Bhavin p On BEST ANSWER

Swift 4: So basically we have a string with commas and we just remove all the commas in the string and then we use NumberFormatter to convert it to a double.

var newDouble = 0.0
var string = ""
string = textField.text?.replacingOccurrences(of: ",", with: "", options: NSString.CompareOptions.literal, range: nil) ?? ""
let myDouble = NumberFormatter().number(from: string)?.doubleValue
newDouble = myDouble ?? 0.0

This code only works properly if there are only numbers and commas.

4
Mojtaba Hosseini On

Use NumberFormatter:

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
let number = formatter.number(from: "1,233,323.32")
0
M Nabeel Hussain On

Swift 4.x:
Here is your solution with Manual Approach

var a = "1,233,323.32"
print(a.contains(","))

check how many time does ',' occurs in a String, given below

print("occurrence of ',': \(a.characters.filter {$0 == ","}.count)")

if ',' occurs 2times in string then remove ',' from String 2time using loop, given below

for _ in 1...(a.characters.filter {$0 == ","}.count)  {
    a.remove(at: a.index(of: ",")!)
}

print("Ans: \( Double(a)! )")

output

true
occurrence of ',': 2
Ans: 1233323.32