1

i'm just in playground trying to get this thing to work, but it doesn't want to work for me..

var total = 1234.1234
var formatter = NSNumberFormatter()
formatter.numberStyle = .CurrencyStyle
println("\(formatter.stringFromNumber(total))")
// Returns: "Optional("$1,234.12")" instead of just "$1,234.12"

I want to show just the formatted number to the user but the extra Optional bit keeps showing up.

fjaxyu
  • 390
  • 1
  • 3
  • 10
  • 2
    Please read the NSNumberFormatter documentation. The return value of `stringFromNumber()` is `String?`. Then read the [Swift documentation](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/) to understand what the question mark means, and what an Optional is ... – Martin R Jan 07 '15 at 17:30
  • As to why this is optional: http://stackoverflow.com/questions/28103113/does-nsnumberformatter-stringfromnumber-ever-return-nil – Thilo Jan 23 '15 at 04:50
  • No idea why this question was downvoted into negative. Seems reasonable to me. – user1244109 Sep 23 '15 at 22:43

1 Answers1

0

Since you're just in playgrounds and are sure that the optional contains a value, you can use forced unwrappping by adding an exclamation mark:

print("\(formatter.stringFromNumber(total)!)")
mtso
  • 111
  • 1
  • 5
  • 8