如何在swift中将Decimal
转换为String
?
例如
let de = Decimal(string: "123")
然后如何将de
转换为String。
发布于 2018-08-08 01:03:30
利用十进制符合CustomStringConvertible
协议这一事实,我会简单地这样做:
let decimalString = "\(de)"
发布于 2018-04-20 18:25:42
转换为NSDecimalNumber并使用stringValue。
NSDecimalNumber(decimal: de).stringValue
发布于 2017-08-10 10:24:00
使用NSNumberFormatter
解析您的输入。将其generatesDecimalNumbers
属性设置为true:
let formatter = NumberFormatter()
formatter.generatesDecimalNumbers = true
下面是你如何使用它,如果你想在字符串不能被解析时返回0:
func decimal(with string: String) -> NSDecimalNumber {
return formatter.number(from: string) as? NSDecimalNumber ?? 0
}
decimal(with: "80.00")
// Result: 80 as an NSDecimalNumber
默认情况下,格式化程序将查看设备的区域设置以确定小数标记。你应该让它保持原样。出于示例的目的,我将其强制转换为法语地区:
// DON'T DO THIS. Just an example of behavior in a French locale.
formatter.locale = Locale(identifier: "fr-FR")
decimal(with: "80,00")
// Result: 80
decimal(with: "80.00")
// Result: 0
如果您确实希望始终使用逗号作为小数标记,则可以设置decimalSeparator
属性:
formatter.decimalSeparator = ","
https://stackoverflow.com/questions/45610567
复制相似问题