gpt4 book ai didi

ios - 有没有兼容Java和Swift的格式说明?

转载 作者:搜寻专家 更新时间:2023-11-01 06:03:49 25 4
gpt4 key购买 nike

在Java中有DecimalFormat支持

  • ###.## -> 3.14
  • 0 -> 3
  • 00.000 -> 03.142
  • #.##% -> 314.16%
  • 饼图是###.## -> 饼图是 3.14

但我在 Swift for iOS 中找不到等效的函数。

NumberFormatter,但是不支持pie is ###.##,代码中设置所有属性不方便:

formatter.maximumFractionDigits = 2
formatter.numberStyle = .currencyAccounting

我很好奇是否有一种格式同时被 Java 和 Swift 支持,这在 React Native 中会非常有用(在 js 中定义格式)

最佳答案

(NS)NumberFormatterpositiveFormatnegativeFormat属性,它们是根据 Unicode Technical Standard #35 的格式模式.这些似乎兼容使用 Java DecimalFormat

例子:

let posNumber = NSNumber(value: Double.pi)
let negNumber = NSNumber(value: -Double.pi)

let f1 = NumberFormatter()
f1.positiveFormat = "00.000"
print(f1.string(from: posNumber)!) // 03.142
print(f1.string(from: negNumber)!) // -03.142

let f2 = NumberFormatter()
f2.positiveFormat = "pie is ###.## "
print(f2.string(from: posNumber)!) // pie is 3.14

数字根据当前语言环境进行格式化(因此输出也可以是 3,14)。如果不是这样,请添加

f2.locale = Locale(identifier: "en_US_POSIX")

如果你不设置 negativeFormat 那么正格式负数将使用前置减号。这在第一个示例中效果很好,但不适用于自定义文本:

print(f2.string(from: negNumber)!) // -pie is 3.14

这通过同时设置正负格式来解决:

let f3 = NumberFormatter()
f3.positiveFormat = "Result is 00.000"
f3.negativeFormat = "Result is -00.000"
print(f3.string(from: posNumber)!) // Result is 03.142
print(f3.string(from: negNumber)!) // Result is -03.142

在 macOS 上,可以使用 format 属性,positive和(可选)否定格式由分号分隔。在上面的示例中:

f2.format = "pie is ###.##"

f3.format = "Result is 00.000;Result is -00.000"

关于ios - 有没有兼容Java和Swift的格式说明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42801717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com