Swift playground - How to convert a string with comma to a string with decimal

前端 未结 5 1782
不知归路
不知归路 2020-12-03 17:52

I\'m new in the Swift world.

How can I converting a String with a comma to a String with a decimal?

The code work\'s fine with a dot (.)

The problem

5条回答
  •  盖世英雄少女心
    2020-12-03 18:30

    EDIT: Updated to work with the current version of Swift:

    let amount = "8,35"
    
    var counter: Int = 0
    var noCommaNumber: String!
    for var carattere in (amount) {
        if carattere == "," { carattere = "." }
        if counter != 0 { noCommaNumber = "\(noCommaNumber ?? "\(carattere)")" + "\(carattere)" } else { noCommaNumber = "\(carattere)" } // otherwise first record will always be nil
        counter += 1
    }
    
    let importo = Float(noCommaNumber)
    

提交回复
热议问题