在 Swift 中将字符串转换为浮点数 [英] Convert String to Float in Swift

查看:60
本文介绍了在 Swift 中将字符串转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试转换从 UITextField 中获取的数字,我认为它实际上是字符串,并将它们转换为浮点数,以便我可以将它们相乘.

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.

我有两个 UITextfield 声明如下:

I have two UITextfields which are declared as follows:

@IBOutlet var wage: UITextField
@IBOutlet var hour: UITextField

当用户按下 UIButton 时,我想计算用户赚取的工资,但我不能,因为我需要先将它们转换为浮点数,然后才能使用它们.

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.

推荐答案

Swift 2.0+

现在有了 Swift 2.0,您可以只使用 Float(Wage.text) 返回一个 Float? 类型.比下面只返回 0 的解决方案更清楚.

Swift 2.0+

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.

如果您出于某种原因想要一个无效 Float0 值,您可以使用 Float(Wage.text) ??0 如果它不是有效的 Float,它将返回 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

我实际上创建了一个 extension 来更好地使用它:

I actually created an extension to better use this too:

extension String {
    var floatValue: Float {
        return (self as NSString).floatValue
    }
}

现在您只需调用 var WageConversion = Wage.text.floatValue 并允许扩展程序为您处理桥接!

Now you can just call var WageConversion = Wage.text.floatValue and allow the extension to handle the bridge for you!

这是一个很好的实现,因为它可以处理实际的浮点数(使用 . 输入)并且还有助于防止用户将文本复制到您的输入字段中(12p.34>,甚至 12.12.41).

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).

显然,如果 Apple 确实向 Swift 添加了 floatValue 这将引发异常,但同时它可能很好.如果他们稍后添加它,那么您修改代码所需要做的就是删除扩展名,一切都会无缝地工作,因为您已经在调用 .floatValue!

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!

另外,变量和常量应该以小写开头(包括IBOutlets)

Also, variables and constants should start with a lower case (including IBOutlets)

这篇关于在 Swift 中将字符串转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆