-3

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).

Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
Bhavin p
  • 98
  • 10

3 Answers3

1

Use NumberFormatter:

let formatter = NumberFormatter()
formatter.numberStyle = .decimal
let number = formatter.number(from: "1,233,323.32")
Mojtaba Hosseini
  • 95,414
  • 31
  • 268
  • 278
  • 2
    Keep in mind that this will probably fail for users in a locale that uses different separators for grouping and decimal. – rmaddy May 28 '19 at 20:48
  • 2
    Yeah but this is ‘StaticString’. – Mojtaba Hosseini May 28 '19 at 20:50
  • 2
    I don't understand the point of your reply. For users in a locale that use `,` for the decimal separator, the value of `number` will be `nil` for a string such as `1,233,323.32`. – rmaddy May 28 '19 at 20:54
  • That's true, it fails for users with locales which use not comma separated decimal values. – Enzo Aug 16 '23 at 08:39
0

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.

Bhavin p
  • 98
  • 10
-1

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