How can I convert NSDecimalNumber values to String?
// Return type is NSDecimalNumber
var price = prod.minimumPrice // 10
// need a String
cell.priceLB.text = NSString(format:"%f", prod.minimumPrice) as String
How can I convert NSDecimalNumber values to String?
// Return type is NSDecimalNumber
var price = prod.minimumPrice // 10
// need a String
cell.priceLB.text = NSString(format:"%f", prod.minimumPrice) as String
You could try some of these options. They all should return 10. And also check why would you need to create NSString formatting the number and casting it to String.
"\(price)"
String(describing: price)
NSString(format: "%@", price)
price.description(withLocale: nil)
which should be used with NSDecimalNumber
instead of NumberFormatter
. –
Eusebiaeusebio NSDecimalValue inherits from NSNumber.
NSNumber have stringValue
property
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.
Two ways:
use NumberFormatter
use stringValue
property directly
Code using NumberFormatter fixed to two decimal places:
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
try this
var price = prod.minimumPrice
cell.priceLB.text = "\(price)"
//or
cell.priceLB.text = String(describing: price)
© 2022 - 2024 — McMap. All rights reserved.