使用 numberFromString 生成 NSDecimalNumber 时如何获得没有分数错误的舍入值?
How to get rounded value without fraction error when using numberFromString to generate NSDecimalNumber?
我正在尝试从字符串中解析出 NSDecimalNumber
,但是无论我在 numberFormatter 上设置什么属性,我都无法让它在获取 numberFromString
[= 时停止出现小数错误13=]
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。我怎样才能让它为数字设置正确的值?
将最后一行替换为
let number = numberFormatter.numberFromString("93.7")?.floatValue
在 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>
我正在尝试从字符串中解析出 NSDecimalNumber
,但是无论我在 numberFormatter 上设置什么属性,我都无法让它在获取 numberFromString
[= 时停止出现小数错误13=]
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。我怎样才能让它为数字设置正确的值?
将最后一行替换为
let number = numberFormatter.numberFromString("93.7")?.floatValue
在 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>