TFLOW9Z1 TFLOW9Z1 - 29 days ago 17
Swift Question

Cannot convert value of type 'Double' to expected argument type 'NSNumber'

func updateCelsiusLabel() {
if let value = celsiusValue {
celsiusLabel.text = numberFormatter.stringFromNumber(value)
}
else {
celsiusLabel.text = "???"
}
}


let numberFormatter: NumberFormatter = {
let nf = NumberFormatter()
nf.numberStyle = .DecimalStyle
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1
return nf
}()


I'm writing code that will creating a celsius format for my iphone application. I need it to handle converting a number into a decimal place.

I"m getting two error from my xcode compiler. Cannot convert value of type 'Double' to expected argument type 'NSNumber'. the other problem, Type 'NumberFormatter.Style' has no member 'DecimalStyle' . need help working out the problem.

Answer

the function stringFromNumber is expecting you to pass it an NSNumber object but you are trying to pass it a Double. So you need to wrap your Double like so:

let myNumber = NSNumber(value: value)
celsiusLabel.text = numberFormatter.string(from: myNumber)

Also I believe it should just be

.decimal

Instead of

.decimalStyle

Note: This could be slightly different depending on the version of swift you are using.

Comments