我正在尝试用swift语言编写一个BMI程序。 我有这个问题:如何转换字符串为双精度?

在Objective-C中,我可以这样做:

double myDouble = [myString doubleValue];

但是如何在Swift语言中实现这一点呢?


当前回答

我们可以使用CDouble值,它将通过myString.doubleValue获得

其他回答

斯威夫特:4和5

可能有两种方法:

String -> Int -> Double: let strNumber = "314" if let intFromString = Int(strNumber){ let dobleFromInt = Double(intFromString) 打印(dobleFromInt) } String -> NSString -> Double 让strNumber1 = "314" 让NSstringFromString = NSString(字符串:strNumber1) let doubleFromNSString = NSstringFromString.doubleValue 打印(doubleFromNSString)

使用它,无论你喜欢根据你需要的代码。

在某些情况下,使用Scanner从字符串中提取数字是一种非常方便的方法。当涉及到解码和处理不同的数字格式和地区时,它几乎和NumberFormatter一样强大。它可以提取具有不同小数和组分隔符的数字和货币。

import Foundation
// The code below includes manual fix for whitespaces (for French case)
let strings = ["en_US": "My salary is $9,999.99",
               "fr_FR": "Mon salaire est 9 999,99€",
               "de_DE": "Mein Gehalt ist 9999,99€",
               "en_GB": "My salary is £9,999.99" ]
// Just for referce
let allPossibleDecimalSeparators = Set(Locale.availableIdentifiers.compactMap({ Locale(identifier: $0).decimalSeparator}))
print(allPossibleDecimalSeparators)
for str in strings {
    let locale = Locale(identifier: str.key)
    let valStr = str.value.filter{!($0.isWhitespace || $0 == Character(locale.groupingSeparator ?? ""))}
    print("Value String", valStr)

    let sc = Scanner(string: valStr)
    // we could do this more reliably with `filter` as well
    sc.charactersToBeSkipped = CharacterSet.decimalDigits.inverted
    sc.locale = locale

    print("Locale \(locale.identifier) grouping separator: |\(locale.groupingSeparator ?? "")| . Decimal separator: \(locale.decimalSeparator ?? "")")
    while !(sc.isAtEnd) {
        if let val = sc.scanDouble() {
            print(val)
        }

    }
}

但是,将分隔符视为单词分隔符存在一些问题。

// This doesn't work. `Scanner` just ignores grouping separators because scanner tends to seek for multiple values
// It just refuses to ignore spaces or commas for example.
let strings = ["en_US": "$9,999.99", "fr_FR": "9999,99€", "de_DE": "9999,99€", "en_GB": "£9,999.99" ]
for str in strings {
    let locale = Locale(identifier: str.key)
    let sc = Scanner(string: str.value)
    sc.charactersToBeSkipped = CharacterSet.decimalDigits.inverted.union(CharacterSet(charactersIn: locale.groupingSeparator ?? ""))
    sc.locale = locale
    print("Locale \(locale.identifier) grouping separator: \(locale.groupingSeparator ?? "") . Decimal separator: \(locale.decimalSeparator ?? "")")
    while !(sc.isAtEnd) {
        if let val = sc.scanDouble() {
            print(val)
        }

    }
}
//     sc.scanDouble(representation: Scanner.NumberRepresentation) could help if there were .currency case

自动检测语言环境是没有问题的。注意,grouingseparator在法语区域设置中的字符串“Mon salaire est 9 999,99€”不是一个空格,尽管它可以完全呈现为空格(这里不是)。这就是为什么下面的代码没有!$0也能正常工作的原因。正在过滤的空白字符。

let stringsArr = ["My salary is $9,999.99",
                  "Mon salaire est 9 999,99€",
                  "Mein Gehalt ist 9.999,99€",
                  "My salary is £9,999.99" ]

let tagger = NSLinguisticTagger(tagSchemes: [.language], options: Int(NSLinguisticTagger.Options.init().rawValue))
for str in stringsArr {
    tagger.string = str
    let locale = Locale(identifier: tagger.dominantLanguage ?? "en")
    let valStr = str.filter{!($0 == Character(locale.groupingSeparator ?? ""))}
    print("Value String", valStr)

    let sc = Scanner(string: valStr)
    // we could do this more reliably with `filter` as well
    sc.charactersToBeSkipped = CharacterSet.decimalDigits.inverted
    sc.locale = locale

    print("Locale \(locale.identifier) grouping separator: |\(locale.groupingSeparator ?? "")| . Decimal separator: \(locale.decimalSeparator ?? "")")
    while !(sc.isAtEnd) {
        if let val = sc.scanDouble() {
            print(val)
        }

    }
}
// Also will fail if groupingSeparator == decimalSeparator (but don't think it's possible)

这是基于@Ryu的回答

只要你在一个用圆点作为分隔符的国家,他的解决方案就很好。默认情况下NSNumberFormatter使用设备区域设置。因此,在所有使用逗号作为默认分隔符的国家(包括法国的@PeterK),这将失败。如果数字使用点作为分隔符(通常情况下)。要将这个NSNumberFormatter的区域设置为US,并使用圆点作为分隔符替换行

return NSNumberFormatter().numberFromString(self)?.doubleValue

with

let numberFormatter = NSNumberFormatter()
numberFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return numberFormatter.numberFromString(self)?.doubleValue

因此,完整的代码变成

extension String {
    func toDouble() -> Double? {
        let numberFormatter = NSNumberFormatter()
        numberFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
        return numberFormatter.numberFromString(self)?.doubleValue
    }
}

要使用它,只需调用"Your text goes here".toDouble()

这将返回一个可选的Double?

正如@Ryu提到的,你可以强制展开:

println("The value is \(myDouble!)") // prints: The value is 4.2

或者使用if let语句:

if let myDouble = myDouble {
    println("The value is \(myDouble)") // prints: The value is 4.2
}

请到操场上检查!

let sString = "236.86"

var dNumber = NSNumberFormatter().numberFromString(sString)
var nDouble = dNumber!
var eNumber = Double(nDouble) * 3.7

顺便说一下,在我的Xcode中

.toDouble() -不存在

从非数值字符串中创建值0.0

1.

let strswift = "12"
let double = (strswift as NSString).doubleValue

2.

var strswift= "10.6"
var double : Double = NSString(string: strswift).doubleValue 

也许这对你有帮助。