首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在swift 4中为每4位数字添加逗号或空格?

如何在swift 4中为每4位数字添加逗号或空格?
EN

Stack Overflow用户
提问于 2018-08-01 07:10:08
回答 1查看 819关注 0票数 -2

我的情况有点特殊,我需要为每4位数字插入空格或逗号。

示例:18686305 1868,6305 or 1868 6305

在swift 4中我该怎么做?

EN

回答 1

Stack Overflow用户

发布于 2018-08-01 07:24:36

NumberFormatter旨在根据预定义的格式将数值转换为String值。在您的示例中,以下代码将每四位插入一次分组分隔符:

代码语言:javascript
复制
import Foundation

let groupingSeparator = "," // determined based on user input, as per the question

let formatter = NumberFormatter()
formatter.positiveFormat = "####,####"
formatter.negativeFormat = "-####,####"
formatter.groupingSeparator = groupingSeparator

if let string = formatter.string(from: 18686305) {
    print(string) // prints "1868,6305"
}

positiveFormatnegativeFormat变量跟在Unicode Technical Standard #35后面。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51623312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档