简体   繁体   English

在Swift中将String小数转换为float还是double?

[英]Converting a String decimal to a float or double in Swift?

I'm trying to convert a String such as "3.9" to a Float value in Swift that will be represented as 3.9 (which can then be used in calculations). 我正在尝试将String(例如“ 3.9”)转换为Swift中的Float值,该值将表示为3.9(然后可以在计算中使用)。 I'm running into issues here as the conversion doesn't seem to be going right, my code looks like this: 由于转换似乎不正确,因此我遇到了问题,我的代码如下所示:

var a:Float = (lastNumber as NSString).floatValue
var b:Float = (answerField!.text! as NSString).floatValue
if (operatorLabel?.text == "+"){
      println(a)
   }

I'm trying to make a basic calculator app, as you can see. 如您所见,我正在尝试制作一个基本的计算器应用程序。 However, when I print the "a" value, it shows up as an error (11db) and I'm not sure how to approach this issue. 但是,当我打印“ a”值时,它显示为错误(11db),并且我不确定如何解决此问题。 Any thoughts? 有什么想法吗? I'm thinking right now that I might be having a problem because the period in "3.9" isn't being converted to a decimal point, but I'm not sure. 我现在正在考虑可能会遇到问题,因为“ 3.9”中的句点没有转换为小数点,但是我不确定。

It's even simpler. 更简单。

let s = "3.9"
let a = Float(s)

Watch out for force unwrapping - and don't make outlet optional. 当心是否需要展开包装-请勿使插座成为可选。

if let st = answerField.text {
   b = Float(s)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM