将NSDecimalNumber转换为字符串

8

如何将 NSDecimalNumber 值转换为字符串?

// Return type is NSDecimalNumber
var price = prod.minimumPrice // 10

// need a String
cell.priceLB.text = NSString(format:"%f", prod.minimumPrice) as String

https://dev59.com/x1oV5IYBdhLWcg3wCq8n - pkamb
4个回答

15

你可以尝试以下几个选项。它们都应该返回10。此外,请检查为什么需要创建NSString格式化数字并将其转换为字符串。

"\(price)"
String(describing: price)
NSString(format: "%@", price)

4
另外,应该使用 price.description(withLocale: nil)NSDecimalNumber 一起使用,而不是 NumberFormatter - Sulthan

8

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.

文档来源

这里是关于IT技术的内容。

4

两种方法:

  1. 使用 NumberFormatter

  2. 直接使用 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


2
尝试这个。
var price = prod.minimumPrice    
cell.priceLB.text = "\(price)"
//or
cell.priceLB.text = String(describing: price)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接