使用numberFromString生成NSDecimalNumber时如何获得舍入值而没有分数错误?

时间:2016-02-02 10:23:35

标签: ios number-formatting nsdecimalnumber

我正在尝试从字符串中解析出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。如何让它为数字设置正确的值?

2 个答案:

答案 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