Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSDecimalNumber to 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
like image 978
Yatish Agrawal Avatar asked Jan 21 '17 08:01

Yatish Agrawal


4 Answers

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)
like image 145
bianca hinova Avatar answered Sep 20 '22 01:09

bianca hinova


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

like image 33
Paul Brewczynski Avatar answered Sep 18 '22 01:09

Paul Brewczynski


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

like image 39
kkklc Avatar answered Sep 21 '22 01:09

kkklc


try this

var price = prod.minimumPrice    
cell.priceLB.text = "\(price)"
//or
cell.priceLB.text = String(describing: price)
like image 35
ItsMeMihir Avatar answered Sep 21 '22 01:09

ItsMeMihir