简体   繁体   English

将Int转换为格式化的字符串(Swift)

[英]Convert Int to a formatted string (Swift)

I am trying to format an int to formatted string, like a 23 -> "0023", 100 -> 0100 and so on. 我正在尝试将int格式化为格式化的字符串,例如23->“ 0023”,100-> 0100,依此类推。 I've finished with the function below, but it eats last digit of every number that is multiple of 10, like 900 becomes 090, instead of 0900. Please help me fix that bug, thanks. 我已经完成了下面的功能,但是它占用了每个数字的最后一位,该数字是10的倍数,例如900变成090,而不是0900。请帮助我修复该错误,谢谢。

func convert(_ score: Int) -> String {
  return String(Float(score) / 1000.0).components(separatedBy: ".").joined()
}

Dividing by 1000 and relying on a certain floating point representation is fragile and a bad idea for this purpose. 除以1000并依靠某个浮点表示形式是脆弱的,并且对于此目的是个坏主意。 A simple solution is to use the %ld format with a minimum of 4 digits: 一个简单的解决方案是使用至少4位数字的%ld格式:

func convert(_ score: Int) -> String {
    return String(format: "%04ld", score)
}

print(convert(23)) // 0023

You can use a NumberFormatter and set minimumIntegerDigits to 4 to achieve your goals. 您可以使用NumberFormatter并将minimumIntegerDigits设置为4来实现您的目标。

let nf = NumberFormatter()
nf.minimumIntegerDigits = 4
nf.locale = Locale(identifier: "en_US_POSIX") // Avoid thousands separator
nf.string(for: 23) //"0023"
nf.string(for: 90) //"0900"

For performance reasons, you should avoid recreating the NumberFormatter instance each time you need it and rather define it in a scope (ie by making it an instance/static property of the relevant class) such that it can be reused. 出于性能方面的考虑,应避免在每次需要时都重新创建NumberFormatter实例,而应在范围内进行定义(例如,通过使其成为相关类的实例/静态属性),以便可以重用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM