Swift Playground-如何将逗号字符串转换为十进制字符串 [英] Swift playground - How to convert a string with comma to a string with decimal
问题描述
我是Swift世界的新手。
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 (.)
问题是当我使用逗号(,)... : var price
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 (.)
如果是关键,则不知道如何使用 NSNumberFormatter 或 generatesDecimalNumbers 。可能有不止一种选择。
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)
感谢您的时间和帮助!
推荐答案
更新: Xcode 8.2.1•Swift 3.0.2
您可以使用NumberFormatter()将字符串转换为数字。您只需要指定小数点分隔符,如下所示:
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"
您还应该使用NumberFormat进行货币格式化,因此创建一个扩展FloatingPoint协议的只读计算属性货币,以从String doubleValue属性返回格式化的字符串。
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"
这篇关于Swift Playground-如何将逗号字符串转换为十进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!