Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 is when I'm using a comma (,) ... with: var price

The origin of the problem is the Decimal french keyboard use a comma (,) instead of a dot (.)

Don't know exactly how to use NSNumberFormatter or generatesDecimalNumbers if it's the key. There's probebly more than one options.

//The answer change if "2,25" or "2.25" is used.

var price      : String = "2,25"
var priceFloat = (price as NSString).floatValue

//I need to have 2.25 as answer.

var costString = String(format:"%.2f", priceFloat)

Thank's for your time and your help!

like image 628
ShakeMan Avatar asked Feb 04 '15 05:02

ShakeMan


1 Answers

update: Xcode 8.2.1 • Swift 3.0.2 You can use NumberFormatter() to convert your string to number. You just need to specify the decimalSeparator as follow:

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


"2.25".doubleValue // 2.25
"2,25".doubleValue // 2.25

let price = "2,25"
let costString = String(format:"%.2f", price.doubleValue)   // "2.25"

You should do the currency formatting also with NumberFormat, so create a read-only computed property currency extending FloatingPoint protocol to return a formatted string from the String doubleValue property.

extension NumberFormatter {
    convenience init(style: Style) {
        self.init()
        self.numberStyle = style
    }
}
extension Formatter {
    static let currency = NumberFormatter(style: .currency)
}
extension FloatingPoint {
    var currency: String {
        return Formatter.currency.string(for: self) ?? ""
    }
}

let costString = "2,25".doubleValue.currency   // "$2.25"

Formatter.currency.locale = Locale(identifier: "en_US")
"2222.25".doubleValue.currency    // "$2,222.25"
"2222,25".doubleValue.currency    // "$2,222.25"

Formatter.currency.locale = Locale(identifier: "pt_BR")
"2222.25".doubleValue.currency    // "R$2.222,25"
"2222,25".doubleValue.currency    // "R$2.222,25"
like image 171
Leo Dabus Avatar answered Sep 18 '22 15:09

Leo Dabus