I'm trying to convert numbers taken from a UITextField, which I presume, are actually Strings, and convert them to Float, so I can multiply them.
I have two UITextfield
s which are declared as follows:
@IBOutlet var wage: UITextField @IBOutlet var hour: UITextField
When the user presses a UIButton I want to calculate the wages the user earns, but I can't, as I need to convert them to floats first, before I can use them.
I know how to convert them to an integer by doing this:
var wageConversion:Int = 0 wageConversion = wage.text.toInt()!
However, I have no idea how to convert them to floats.
If the String contains a valid floating point value, then Swift will assign it to the floatValue constant which will be available within the if let scope. The result of this example will be printed as “Float value = 12.2416”.
It is best to create a NSNumberFormatter to convert a string to float. Show activity on this post. I think this is the best solution (at least for swift 4+), the main reason being that it returns an optional (as opposed to NSString. floatValue , which simply return 0 if something is wrong.).
To convert a string to a double, we can use the built-in Double() initializer syntax in Swift. The Double() initializer takes the string as an input and returns the double instance.
Swift provides two signed floating-point number types: Double represents a 64-bit floating-point number. Float represents a 32-bit floating-point number.
Now with Swift 2.0 you can just use Float(Wage.text)
which returns a Float?
type. More clear than the below solution which just returns 0
.
If you want a 0
value for an invalid Float
for some reason you can use Float(Wage.text) ?? 0
which will return 0
if it is not a valid Float
.
The best way to handle this is direct casting:
var WageConversion = (Wage.text as NSString).floatValue
I actually created an extension
to better use this too:
extension String { var floatValue: Float { return (self as NSString).floatValue } }
Now you can just call var WageConversion = Wage.text.floatValue
and allow the extension to handle the bridge for you!
This is a good implementation since it can handle actual floats (input with .
) and will also help prevent the user from copying text into your input field (12p.34
, or even 12.12.41
).
Obviously, if Apple does add a floatValue
to Swift this will throw an exception, but it may be nice in the mean time. If they do add it later, then all you need to do to modify your code is remove the extension and everything will work seamlessly, since you will already be calling .floatValue
!
Also, variables and constants should start with a lower case (including IBOutlets
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With