ios - 如何在 Int 和 Float 类型中添加千位分隔符?
问题描述
我有一个关于添加千位分隔符的问题。
我有三种类型的数字字符串。
我在这里的堆栈中找到了答案。
但我尝试使用它,并未能添加千位分隔符。
对我有什么想法吗?谢谢。
let str = "1000"
let string1 = "5000.000"
let string2 = "2000.0"
let convertStr = str.formattedWithSeparator //in playground, get error 「Value of type 'String' has no member 'formattedWithSeparator'」.
let convertStr1 = Float(string1)!.formattedWithSeparator //get error too.
let convertStr2 = Float(string2)!.formattedWithSeparator //get error too.
extension Formatter {
static let withSeparator: NumberFormatter = {
let formatter = NumberFormatter()
formatter.groupingSeparator = ","
formatter.numberStyle = .decimal
return formatter
}()
}
extension BinaryInteger {
var formattedWithSeparator: String {
return Formatter.withSeparator.string(for: self) ?? ""
}
}
解决方案
数字格式化程序不以“数字字符串”开头;他们以数字开头。因此,例如,使用您已经拥有的 Formatter 扩展代码:
let n = 5000
let s = Formatter.withSeparator.string(for: n)
// s is now "5,000"
但是让我们说你开始的真正是一个字符串。然后你可以说,例如:
let str = "5000"
let s = Formatter.withSeparator.string(for: Float(str)!)
// s is now "5,000"
请注意,在此过程中会丢失十进制信息。如果这对您很重要,您需要将该要求添加到格式化程序本身。您正在制作一个字符串,并且您必须提供有关您希望该字符串的外观的所有信息。例如:
let str = "5000.00"
let f = Formatter.withSeparator
f.minimumFractionDigits = 2
let s = f.string(for: Float(str)!)
// s is now "5,000.00"
如果你省略了mimimumFractionDigits
信息,你会"5,000"
再次得到;我们开始使用的字符串的原始外观完全不重要。
推荐阅读
- html - 我如何在 explorer 11 中使用 FrameSet?
- selenium - 使用 Selenium 框架截屏时发生“TypeError: rootNode is null”
- r - 只有当它们与上面和下面的行相同时,如何删除行?
- python - 过滤日期在多个给定日期的 +/-30 天内的数据
- ios - 从 -traitCollection 返回 nil,这在 Xcode 11 Beta 中是不允许的
- amazon-web-services - 如何解决错误““消息”:“用户:匿名无权执行:iam:PassRole on resource”
- vue.js - 如何居中对齐表格 - PDFMAKE
- c# - asp:GridView -> asp:TemplateField 调用公共方法在控件内部不可用
- javascript - 使用 javascript/jQuery 从路径获取图像时发现重复的结果
- javascript - 谷歌分析页面数据和 api 响应之间是不同的