Convert NSDecimalNumber to String
Asked Answered
S

4

8

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
Selfsame answered 21/1, 2017 at 8:9 Comment(1)
#36794989Spider
H
15

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)
Humour answered 21/1, 2017 at 8:20 Comment(1)
Also, there is price.description(withLocale: nil) which should be used with NSDecimalNumber instead of NumberFormatter.Eusebiaeusebio
H
8

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.

Documentation Source

Huelva answered 20/4, 2017 at 23:8 Comment(0)
U
4

Two ways:

  1. use NumberFormatter

  2. 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

Unconscionable answered 1/11, 2019 at 10:0 Comment(0)
R
2

try this

var price = prod.minimumPrice    
cell.priceLB.text = "\(price)"
//or
cell.priceLB.text = String(describing: price)
Rosalba answered 21/1, 2017 at 9:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.