在maximumFractionDigits中应该如何设置才能减少数据损失?

问题描述 投票:-1回答:1

介紹

我注意到 NumberFormatter#maximumFractionDigits 默认为3。

我已经确认了。

import Foundation

let nf = NumberFormatter()
nf.numberStyle = .decimal
print(nf.maximumFractionDigits) //=> 3
nf.string(for: Decimal(string: "100.1111111")) //=> "100.111"

我已经尝试设置Int. max

我设置 Int.maxmaximumFractionDigits:

import Foundation

let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.maximumFractionDigits = Int.max
nf.string(for: Decimal(string: "100.1111111")) // => "100"

为什么?"100"!?

在我的研究中

我读到 Foundation > NSNumberFormatter > NumberFormatter 源代码。

open var maximumFractionDigits: Int

我已经确认 maximumFractionDigits 数据类型为 Int.

问题

如何将最大值设置为 maximumFractionDigits?

我想尽可能无损地显示一个服务器的响应,当然,服务器的响应就是 Stringjson. 但所有的大多数计算在ios应用程序与 Decimal 来自 String. 所以,这个目标是转换 DecimalString 对于 UILabel.

  • Q1. nf.maximumFractionDigits = Int.max. 为什么会丢失数据?NumberFormatter?
  • Q2. 如何将最大值设置为 maximumFractionDigits 正确吗?

目标

我想尽量减少数据损失。

ios swift formatting
1个回答
1
投票

Q1. nf.maximumFractionDigits = Int.max. 为什么会丢失数据,这是NumberFormatter的bug吗?

当没有明确记录时,每个 Int 参数可能有一个限制,这取决于实现的细节。如果你传递的值超过了这个限制,运行时可能会出现错误,导致崩溃,或者被默默地忽略,这些都取决于实现的细节。

据我测试,你可以设置的最大数量为 maximumFractionDigits 是相同的值与 Int32.max.

let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.maximumFractionDigits = Int(Int32.max)+1
print(nf.string(for: Decimal(string: "123.45678901234567890123456789012345678"))!)
//->123
nf.maximumFractionDigits = Int(Int32.max)
print(nf.string(for: Decimal(string: "123.45678901234567890123456789012345678"))!)
//->123.45678901234567890123456789012345678

你可以叫它 窃听器但是,最大的有效数字是 NumberFormatter 能处理的是38位数,其中 Decimal. 谁想为比预期实用值大几百万倍的数值做一个精确的定义?

Q2. 如何正确地将max设置成maximumFractionDigits?

如上所述,max中的重要数字在 Decimal 是38。你可以写这样的东西。

let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.usesSignificantDigits = true
nf.maximumSignificantDigits = 38
print(nf.string(for: Decimal(string: "123.45678901234567890123456789012345678"))!)
//->123.45678901234567890123456789012345678
© www.soinside.com 2019 - 2024. All rights reserved.