Search code examples
iosstringswiftdoublensnumber

Negative String do decimal nsnumber


Im trying to convert a String to a decimal Double or NSNumber.

Heres my string :

"-2000" or "2000"

which should become :

-20.00 or 20.00

already tried :

print("NSNumber \(NSNumberFormatter().numberFromString(amount)!.decimalValue)")
print("Double \(Double(amount))")

but when its negative return nil, or when its positive returns only one number after the comma.


Solution

  • You can do

    Double(("-2000" as NSString).doubleValue / 100)
    

    I would create a simple extension (String+decimalPrice.swift) for that

    extension String {
        var decimalPrice: Double {
            return (self as NSString).doubleValue / 100
        }
    }
    
    let price = "-999".decimalPrice
    print(price) # -> -9.99