Reputation: 763
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.
Upvotes: 1
Views: 1218
Reputation: 17737
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
Upvotes: 0
Reputation: 51
Quick way to convert a String into a NSNumber and then print it with 2 numbers after the comma
let value = "-2000"
let f = NSNumberFormatter()
f.numberStyle = .DecimalStyle
let n = f.numberFromString(value)!
NSLog("%.2f", n.floatValue)
Upvotes: 0
Reputation: 13230
var amount = "-2000" // String
var doubleNumber = Double(amount / 100)! // Double
var stringWithFormat = NSString(format: "formatted number %.2f", doubleNumber) // to get String with your format
When variable is Double. -20.0 and -20.00 are same value. Only if variable is String "-20.0" and "-20.00" are different
Upvotes: 1