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).
In a string with just numbers and commas how do I convert that into a double
579 Views Asked by Bhavin p At
3
There are 3 best solutions below
4
On
Use NumberFormatter:
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
let number = formatter.number(from: "1,233,323.32")
0
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
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.
This code only works properly if there are only numbers and commas.