将 NSDecimalNumber 转换为字符串
Convert NSDecimalNumber to String
如何将 NSDecimalNumber 值转换为字符串?
// Return type is NSDecimalNumber
var price = prod.minimumPrice // 10
// need a String
cell.priceLB.text = NSString(format:"%f", prod.minimumPrice) as String
您可以尝试其中的一些选项。他们都应该 return 10。还要检查为什么需要创建 NSString 格式化数字并将其转换为 String。
"\(price)"
String(describing: price)
NSString(format: "%@", price)
试试这个
var price = prod.minimumPrice
cell.priceLB.text = "\(price)"
//or
cell.priceLB.text = String(describing: price)
NSDecimalValue 继承自 NSNumber。
NSNumber 有 stringValue
属性
var stringValue: String { get }
The number object's value expressed as a human-readable string.
The string is created by invoking description(withLocale:) where locale is nil.
两种方式:
使用NumberFormatter
直接使用stringValue
属性
使用固定为两位小数的 NumberFormatter 的代码:
Swift 5
let number = NSDecimalNumber(string: "1.1")
print(number.stringValue) //"1.1"
let fmt = NumberFormatter()
fmt.numberStyle = .none;
fmt.minimumFractionDigits = 2;
fmt.minimumIntegerDigits = 1;
fmt.roundingMode = .halfUp;
let result = fmt.string(from: number) ?? "0.00"
//1.10
如何将 NSDecimalNumber 值转换为字符串?
// Return type is NSDecimalNumber
var price = prod.minimumPrice // 10
// need a String
cell.priceLB.text = NSString(format:"%f", prod.minimumPrice) as String
您可以尝试其中的一些选项。他们都应该 return 10。还要检查为什么需要创建 NSString 格式化数字并将其转换为 String。
"\(price)"
String(describing: price)
NSString(format: "%@", price)
试试这个
var price = prod.minimumPrice
cell.priceLB.text = "\(price)"
//or
cell.priceLB.text = String(describing: price)
NSDecimalValue 继承自 NSNumber。
NSNumber 有 stringValue
属性
var stringValue: String { get }
The number object's value expressed as a human-readable string.
The string is created by invoking description(withLocale:) where locale is nil.
两种方式:
使用
NumberFormatter
直接使用
stringValue
属性
使用固定为两位小数的 NumberFormatter 的代码:
Swift 5
let number = NSDecimalNumber(string: "1.1")
print(number.stringValue) //"1.1"
let fmt = NumberFormatter()
fmt.numberStyle = .none;
fmt.minimumFractionDigits = 2;
fmt.minimumIntegerDigits = 1;
fmt.roundingMode = .halfUp;
let result = fmt.string(from: number) ?? "0.00"
//1.10