如何设置`maximumFractionDigits` max?

时间:2018-07-27 00:28:39

标签: ios swift

我发现let的默认值为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

maximumFractionDigits

为什么!?成为import Foundation let nf = NumberFormatter() nf.numberStyle = .decimal nf.maximumFractionDigits = Int.max nf.string(for: Decimal(string: "100.1111111")) // => "100" !!

我阅读了"100"源代码。

  

open var maximumFractionDigits:Int

Foundation > NSNumberFormatter > NumberFormatter数据类型为maximumFractionDigits

如何将max设置为Int

我想尽可能显示服务器响应而不会丢失。 当然,服务器响应是maximumFractionDigits中的String。但是,大多数json中的Decimal都在ios应用中进行计算。因此,此目标是将String的{​​{1}}转换为Decimal

  • Q1。 String。为什么会丢失数据?这是UILabel上的错误吗?
  • 第二季度。如何将max设置为正确的nf.maximumFractionDigits = Int.max

1 个答案:

答案 0 :(得分:1)

问题1。 nf.maximumFractionDigits =最大整数为什么会丢失数据?这是NumberFormatter上的错误吗?

如果没有明确记录,则每个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

您可以将其称为“错误”(em),但是NumberFormatter可以处理的最大有效位数为Decimal的38位。谁想对比实际预期值大百万倍的值进行精确定义?

第二季度。如何将max正确地设置为maximumFractionDigits?

如上所述,Decimal中保留的有效数字为38。您可以这样写:

let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.usesSignificantDigits = true
nf.maximumSignificantDigits = 38
print(nf.string(for: Decimal(string: "123.45678901234567890123456789012345678"))!)
//->123.45678901234567890123456789012345678
相关问题