-3
@IBOutlet weak var creditCardTXTField: UITextField!

 @IBOutlet weak var phoneNUmberTxtField: UITextField!

I have two UITextFields .When I enter a number in the first textfield it should return a float value. for eg if I enter 15 it should return 15.00. This should happen when i click the second UItextfield. (didEndEditing method is used here)

Rakesh Mohan
  • 601
  • 2
  • 11
  • 23

3 Answers3

1
import UIKit

class ViewController: UIViewController , UITextFieldDelegate
{


@IBOutlet weak var one: UITextField!

@IBOutlet weak var two: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}



func textFieldShouldReturn(textField: UITextField) -> Bool {
    return true
}

func textFieldDidEndEditing(textField: UITextField) {

    let myInt = Int(one.text!)

    let myFloat = Float(myInt!)

    two.text = ("\(myFloat)")

}
}
Jigar Tarsariya
  • 3,189
  • 3
  • 14
  • 38
ismael33
  • 1,069
  • 8
  • 5
0

Try this code to convert your int value to float

let myInt = //your int value
let myFloat = Float(myInt)

Or to convert Float to Int you may use

var IntValue:Int = Int(FloatValue)
println "My value is \(IntValue)"

var myIntValue = Int(FloatValue)
0

You can display textfield value as a float like appending ".00" string with textField like,

func textFieldDidEndEditing(textField: UITextField)
{
     if(textField == self.phoneNUmberTxtField)
     {
           self.creditCardTXTField.text = String(format:"%.2f", (Float)(self.creditCardTXTField.text!)!)
     }

}

NOTE: this thing also possible with textFieldShouldReturn method.

Hope this will help you

Jigar Tarsariya
  • 3,189
  • 3
  • 14
  • 38
  • I believe appending ".00 " is not a solution.. If i give 34.5 the output will be 34.500. Instead the output should be 34.5 itself. @JIgar Tarsariya – Rakesh Mohan May 24 '16 at 06:13
  • Ohh, i got it so you can write like my edited answer. please check it. – Jigar Tarsariya May 24 '16 at 06:26
  • @JigarTarsariya Now you copied from my code in comment. Well your code still has bug. Replace `if(textField == self.creditCardTXTField)` with `if(textField == self.phoneNUmberTxtField)` because he need this when he click on second field. – TheTiger May 24 '16 at 07:02
  • @TheTiger As Rakesh Mohan has explained me, i got the idea and change it as he need so no need to copy it because its common to convert string to float and assign it to string again. – Jigar Tarsariya May 24 '16 at 07:07
  • @JigarTarsariya I'm not arguing.. Its ok. But sometimes copy paste left en error as you did. Also `String(format:"%.2f", (Float)(self.creditCardTXTField.text!)!)` here is an unwrapping error `!` I checked it later and you pasted the same so I said that. :) – TheTiger May 24 '16 at 07:14