有没有兼容Java和Swift的格式说明?
Is there any format description compatible with Java and Swift?
在Java中有DecimalFormat
支持
###.##
-> 3.14
0
-> 3
00.000
-> 03.142
#.##%
-> 314.16%
pie is ###.##
-> 饼图是 3.14
但我在 Swift 中找不到 iOS 的等效函数。
有NumberFormatter
,但不支持pie is ###.##
,代码中设置所有属性不方便:
formatter.maximumFractionDigits = 2
formatter.numberStyle = .currencyAccounting
我很好奇是否有Java和Swift都支持的格式,这在React Native中非常有用(在js中定义格式)
(NS)NumberFormatter
有 positiveFormat
和 negativeFormat
属性,它们是根据 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
属性 代替,肯定的
和(可选)否定格式由分号分隔。
在上面的例子中是:
f2.format = "pie is ###.##"
f3.format = "Result is 00.000;Result is -00.000"
在Java中有DecimalFormat
支持
###.##
-> 3.140
-> 300.000
-> 03.142#.##%
-> 314.16%pie is ###.##
-> 饼图是 3.14
但我在 Swift 中找不到 iOS 的等效函数。
有NumberFormatter
,但不支持pie is ###.##
,代码中设置所有属性不方便:
formatter.maximumFractionDigits = 2
formatter.numberStyle = .currencyAccounting
我很好奇是否有Java和Swift都支持的格式,这在React Native中非常有用(在js中定义格式)
(NS)NumberFormatter
有 positiveFormat
和 negativeFormat
属性,它们是根据 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
属性 代替,肯定的
和(可选)否定格式由分号分隔。
在上面的例子中是:
f2.format = "pie is ###.##"
f3.format = "Result is 00.000;Result is -00.000"