栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Swift中将千位分隔符添加到Int

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Swift中将千位分隔符添加到Int

您可以使用NSNumberFormatter指定其他分组分隔符,如下所示:

更新: Xpre 11.5•Swift 5.2

extension Formatter {    static let withSeparator: NumberFormatter = {        let formatter = NumberFormatter()        formatter.numberStyle = .decimal        formatter.groupingSeparator = " "        return formatter    }()}

extension Numeric {    var formattedWithSeparator: String { Formatter.withSeparator.string(for: self) ?? "" }}

2358000.formattedWithSeparator  // "2 358 000"2358000.99.formattedWithSeparator  // "2 358 000.99"let int = 2358000let intFormatted = int.formattedWithSeparator  // "2 358 000"let decimal: Decimal = 2358000let decimalFormatted = decimal.formattedWithSeparator  // "2 358 000"let decimalWithFractionalDigits: Decimal = 2358000.99let decimalWithFractionalDigitsFormatted = decimalWithFractionalDigits.formattedWithSeparator // "2 358 000.99"

如果您需要使用当前语言环境或固定语言环境将值显示为货币:

extension Formatter {    static let number = NumberFormatter()}extension Locale {    static let englishUS: Locale = .init(identifier: "en_US")    static let frenchFR: Locale = .init(identifier: "fr_FR")    static let portugueseBR: Locale = .init(identifier: "pt_BR")    // ... and so on}extension Numeric {    func formatted(with groupingSeparator: String? = nil, style: NumberFormatter.Style, locale: Locale = .current) -> String {        Formatter.number.locale = locale        Formatter.number.numberStyle = style        if let groupingSeparator = groupingSeparator { Formatter.number.groupingSeparator = groupingSeparator        }        return Formatter.number.string(for: self) ?? ""    }    // Localized    var currency:   String { formatted(style: .currency) }    // Fixed locales    var currencyUS: String { formatted(style: .currency, locale: .englishUS) }    var currencyFR: String { formatted(style: .currency, locale: .frenchFR) }    var currencyBR: String { formatted(style: .currency, locale: .portugueseBR) }    // ... and so on    var calculator: String { formatted(groupingSeparator: " ", style: .decimal) }}

用法:

1234.99.currency    // "$1,234.99"1234.99.currencyUS  // "$1,234.99"1234.99.currencyFR  // "1 234,99 €"1234.99.currencyBR  // "R$ 1.234,99"1234.99.calculator  // "1 234.99"

注意:如果您希望空格的宽度等于句点的宽度,则可以使用

"u{2008}"

Unipre空间

formatter.groupingSeparator = "u{2008}"


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636294.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号