KristianC
KristianC

Reputation: 35

Simple calculation in Swift2

Just trying my first simple attempt on a calculation in swift2, but I can't seem to get it right. I have a UITextField input called ValueA I want to du the following calculation on that input (i can have decimals) (((ValueA * ValueA)+3)*1.36) The result must return a number with up to two decimals. I have tried the following:

let kw = 1.36
let three: Double = 3
var a: Double = NSString(string: ValueA.text!).doubleValue
var b: Double = NSString(string: ValueB.text!).doubleValue
var answer:Double = (((a * a) + three) * kw)
let answerFormatter = NSNumberFormatter()
answerFormatter.minimumFractionDigits = 2
answerFormatter.maximumFractionDigits = 2
let Ranswer = answerFormatter.stringFromNumber(answer)!
Result.text = Ranswer`

It kindda works, but sometimes my simulator crashes and sometimes it gets me the right answer but with more decimals as zeroes eg: 45.23000000 (instead of 45.23)

Can someone clean up my code? The answer need to go back into a textfield. Remember I am a total newbee in swift :)

Upvotes: 0

Views: 98

Answers (2)

Code Different
Code Different

Reputation: 93151

You are assuming that the always enter a valid number into ValueA and ValueB. That's one possible source for the crash. Better check that the text can be converted to numbers.

Try this (not tested):

let kw = 1.36
let three = 3.0

if let a = Double(ValueA.text!), b = Double(ValueB.text!) {
    let answer = (((a * a) + three) * kw)

    let answerFormatter = NSNumberFormatter()
    answerFormatter.minimumFractionDigits = 2
    answerFormatter.maximumFractionDigits = 2

    let Ranswer = answerFormatter.stringFromNumber(answer)!
    Result.text = Ranswer
} else {
    print("You must enter a number into ValueA and ValueB")
}

Upvotes: 0

Akshansh Thakur
Akshansh Thakur

Reputation: 5331

You can use something like this

let kw = 1.36
let three: Double = 3
var a = Double(ValueA.text!)!
var b = Double(ValueB.text!)!
var answer = (((a * a) + three) * kw)


 let Ranswer = String(format:"%.2f", answer)
Result.text = Ranswer

And are you sure you wanna do a * a? and not a * b. Just making sure, because you arent using b anywhere

you can also use

let Ranswer = Double(round(100 * answer)/100)
Result.text = String(Ranswer)

Source of information : link

Upvotes: 1

Related Questions