0

Check this out:

(lldb) po NSNumberFormatter().numberFromString("+10.6")
nil
(lldb) po NSNumberFormatter().numberFromString("10.6")
▿ Optional(10.6)
(lldb) po NSNumberFormatter().numberFromString("-10.6")
▿ Optional(-10.6)

So apparently, adding a minus sign to a number is perfectly valid, but a plus sign is not. Is this expected behaviour, and it so, anyone know why?

Maury Markowitz
  • 9,082
  • 11
  • 46
  • 98

2 Answers2

1

I can't say why NSNumberFormatter doesn't tolerate the "+" sign but Swift's Float type seems to be smarter:

 Float("10.6")    --> 10.6
 Float("+10.6")   --> 10.6
 Float("-10.6")   --> -10.6
 Float("Garbage") --> nil

It doesn't return an NSNumber but I guess you could always type cast/convert it.

Alain T.
  • 40,517
  • 4
  • 31
  • 51
0

The problem is that no locale uses a positive prefix by default in their number formatters.

You need to explicitly tell your NSNumberFormatter instance what to do.

This works in Xcode playground:

import Foundation

// this outputs "nil"
let bustedNnumber = NSNumberFormatter().numberFromString("+10.6")

// this outputs "-10.6"
let minusnumber = NSNumberFormatter().numberFromString("-10.6")

let nf = NSNumberFormatter()
nf.numberStyle = .DecimalStyle
nf.positivePrefix = "+"

// this outputs "10.6"
let positiveNumber = nf.numberFromString("+10.6")
Community
  • 1
  • 1
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • Unfortunately, that means that `let enum = nf.numberFromString("10.6")` returns nil, so it's not a universal solution unless I'm missing something. – Maury Markowitz Feb 28 '16 at 15:40