我正在尝试从字符串中解析出NSDecimalNumber
,但无论我在numberFormatter上设置什么属性,我都无法在获取numberFromString
}时停止发出分数错误
let numberFormatter = NSNumberFormatter()
numberFormatter.maximumFractionDigits = 1
numberFormatter.decimalSeparator = "."
numberFormatter.generatesDecimalNumbers = true
numberFormatter.roundingMode = .RoundDown
numberFormatter.roundingIncrement = 0.01
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
let number = numberFormatter.numberFromString("93.9")
数字设置为93.9000000000001,而不是93.9。如何让它为数字设置正确的值?
答案 0 :(得分:1)
在NSDecimalNumber
上定义了一个带有字符串的工厂方法:
+ (NSDecimalNumber *)decimalNumberWithString:(NSString *)numericString
示例:
$ swift
Welcome to Apple Swift version 2.1.1 (swiftlang-700.1.101.15 clang-700.1.81). Type :help for assistance.
1> import Foundation
2> NSDecimalNumber(string: "93.9")
$R0: NSDecimalNumber = 93.9
3>
答案 1 :(得分:0)
用
替换最后一行let number = numberFormatter.numberFromString("93.7")?.floatValue