我目前有一个这样的字符串:"8,0"
或"4,25"
,我需要将其转换为Double
,但我该怎么做?
我是否首先将,
替换为.
?
我查看了NSNumberFormatter
,但每个字符串都返回nil
。
let formatter = NSNumberFormatter()
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
let grade = formatter.numberFromString(grade["Cijfer"].stringValue)
print(grade)
我应该使用什么?
答案 0 :(得分:10)
使用decimalSeparator
:
let formatter = NSNumberFormatter()
formatter.decimalSeparator = ","
let grade = formatter.numberFromString("2,3")
if let doubleGrade = grade?.doubleValue {
print(doubleGrade)
} else {
print("not parseable")
}
打印
2.3
答案 1 :(得分:5)
'纯'斯威夫特(没有基金会)
let str = "9,8"
let sstr = str.characters.split(",").joinWithSeparator(["."])
if let d = Double(String(sstr)) {
print(d) // 9.8
}
答案 2 :(得分:1)
健壮的字符串扩展名
extension String {
var preparedToDecimalNumberConversion: String {
split {
!CharacterSet(charactersIn: "\($0)").isSubset(of: CharacterSet.decimalDigits)
}.joined(separator: ".")
}
}
func testPreparingToDecimalNumberConversion() {
XCTAssertEqual("25.5".preparedToDecimalNumberConversion, "25.5")
XCTAssertEqual("25,5".preparedToDecimalNumberConversion, "25.5")
XCTAssertEqual("...,,,25,5,,,".preparedToDecimalNumberConversion, "25.5")
XCTAssertEqual("25.5,42,..".preparedToDecimalNumberConversion, "25.5.42")
XCTAssertEqual(".42,..".preparedToDecimalNumberConversion, "42")
XCTAssertEqual(".36,,,6,..".preparedToDecimalNumberConversion, "36.6")
XCTAssertEqual("36......6".preparedToDecimalNumberConversion, "36.6")
XCTAssertEqual("36.,.,.,6".preparedToDecimalNumberConversion, "36.6")
XCTAssertEqual(Float("25.5".preparedToDecimalNumberConversion), 25.5)
XCTAssertEqual(Float("25,5".preparedToDecimalNumberConversion), 25.5)
XCTAssertEqual(Float("...,,,25,5,,,".preparedToDecimalNumberConversion), 25.5)
XCTAssertEqual(Float("25.5,42,..".preparedToDecimalNumberConversion), nil)
XCTAssertEqual(Float(".42,..".preparedToDecimalNumberConversion), 42)
}