在Swift中添加千位分隔符到Int [英] Adding Thousand Separator to Int in Swift

查看:612
本文介绍了在Swift中添加千位分隔符到Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Swift相当新,并且在寻找添加空间作为千分隔符的方法时遇到了很多麻烦。

I am fairly new to Swift and having a great deal of trouble finding a way to add a space as a thousand separator.

我希望实现的是获取计算结果并将其显示在文本字段中,以便格式为:

What I am hoping to achieve is taking the result of a calculation and displaying it in a textfield so that the format is:


2 358 000

2 358 000

而不是


2358000

2358000

例如。

我不确定是否应该格式化Int值,然后将其转换为String,或者在Int值转换为String后添加空格。任何帮助将不胜感激。

I am not sure if I should be formatting the Int value and then converting it to a String, or adding the space after the Int value is converted to a String. Any help would be greatly appreciated.

推荐答案

您可以使用NSNumberFormatter指定不同的分组分隔符,如下所示:

You can use NSNumberFormatter to specify a different grouping separator as follow:

更新: Xcode 9•Swift 4

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) ?? ""
    }
}






Xcode 8.3.2•Swift 3.1

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

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







let myInt = 2358000
let myIntString = myInt.formattedWithSeparator  // "2 358 000"

注意:如果您希望有一个宽度相同的空间,可以使用\u {2008}

Note: If you would like to have a space with the same width of a period you can use "\u{2008}"

unicode空格

formatter.groupingSeparator = "\u{2008}"

这篇关于在Swift中添加千位分隔符到Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆