NumberFormatter的异常行为

时间:2018-10-05 02:57:48

标签: swift

我在Swift的NumberFormatter中发现了一个奇怪的行为。

func testNumberFormat() {
    let numberFormat = { (number: NSNumber) -> (String?) in
        let formatter: NumberFormatter = NumberFormatter()
        formatter.numberStyle = .decimal
        formatter.maximumFractionDigits = 2
        formatter.minimumFractionDigits = 2
        formatter.roundingMode = .halfUp

        return formatter.string(from: number)
    }

    XCTAssertEqual(numberFormat(Decimal(0.004) as NSNumber)!, "0.00") // OK
    XCTAssertEqual(numberFormat(Decimal(0.005) as NSNumber)!, "0.01") // OK
    XCTAssertEqual(numberFormat(Decimal(10000.004) as NSNumber)!, "10,000.00") // OK
    XCTAssertEqual(numberFormat(Decimal(10000.005) as NSNumber)!, "10,000.01") // NG!
    XCTAssertEqual(numberFormat(Decimal(10000.014) as NSNumber)!, "10,000.01") // OK
    XCTAssertEqual(numberFormat(Decimal(10000.015) as NSNumber)!, "10,000.02") // OK
}

以下测试失败。

XCTAssertEqual(numberFormat(Decimal(10000.005) as NSNumber)!, "10,000.01") 

我希望返回“ 10,000,01”,但返回“ 10,000,00”。 我的理解有误吗?

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

$scope.data = array

$scope.data = []
tempStore = (event, data) => {
  var array = _(data.context)
      .groupBy('name')
      .map((values,key) => ({key,values}))
      .value()
  $scope.data = array
  console.log( $scope.data)
}
$rootScope.$on('dataStored', tempStore)
console.log tempStore

您知道print(Decimal(10000.005)) //->10000.004999999997952 将与您的10000.004999999997952一起格式化为10,000.00

二进制浮点numberFormat不能表示Double的精确值,因此10000.005的结果很难预测。

如果要在Decimal.init(_: Double)中保留精确的小数表示,则应改用Decimal

Decimal(string:)

如果您想将print(Decimal(string: "10000.005")!) //->10000.005 print(numberFormat(Decimal(string: "10000.005")! as NSNumber)!) //->10,000.01 转换为Double并精确表示一个Decimal ed值,则可能需要更多代码。