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
pkamb
  • 33,281
  • 23
  • 160
  • 191
Yatish Agrawal
  • 452
  • 5
  • 15
  • https://stackoverflow.com/questions/36794489/how-to-get-local-currency-for-skproduct-display-iap-price-in-swift – pkamb Nov 02 '19 at 00:16

4 Answers4

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)
Sulthan
  • 128,090
  • 22
  • 218
  • 270
bianca hinova
  • 576
  • 7
  • 18
  • 4
    Also, there is `price.description(withLocale: nil)` which should be used with `NSDecimalNumber` instead of `NumberFormatter`. – Sulthan Jan 21 '17 at 13:14
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

Paweł Brewczynski
  • 2,665
  • 3
  • 30
  • 43
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

pkamb
  • 33,281
  • 23
  • 160
  • 191
kkklc
  • 149
  • 7
2

try this

var price = prod.minimumPrice    
cell.priceLB.text = "\(price)"
//or
cell.priceLB.text = String(describing: price)
pkamb
  • 33,281
  • 23
  • 160
  • 191
ItsMeMihir
  • 294
  • 1
  • 5
  • 18