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

前端 未结 5 1765
不知归路
不知归路 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:42

    Nullable extension version:

    extension String 
    {
        static let customNumberFormatter = NumberFormatter()
        var doubleValue: Double? {
            String.customNumberFormatter.decimalSeparator = "."
            if let result =  String.customNumberFormatter.number(from: self) {
                return result.doubleValue
            } else {
                String.customNumberFormatter.decimalSeparator = ","
                if let result = String.customNumberFormatter.number(from: self) {
                    return result.doubleValue
                }
            }
            return nil
        }
    }
    

提交回复
热议问题