快速数字格式 [英] Swift number formatting

查看:187
本文介绍了快速数字格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



例如,我需要显示一个数字格式一个至少有两位数的整数(例如00,01,02,03,04,05 ...)。我期望的正常语法是这样的:



println(%02i%02i%02i,var1,var2,var3);



...但我没有找到任何明确的指示如何在Swift中实现这一点。我觉得很难相信我需要创建一个自定义函数来做到这一点。



我发现了一些类似问题的链接(& 如何在Swift中使用println格式化数字),但他们似乎混合目标C,甚至谈论Python和使用统一图书馆。这种基本的编程需求是否没有Swift解决方案? Swift中完全忽略了这么基本的东西是不是真的?

解决方案

您可以使用此构造函数构造一个类似于c的格式的字符串:

  String(format:String,arguments:[CVarArgType])







$ b println(String(format: %04d,arguments:[x]))//这将打印0010

你会使用它很多,并希望一个更紧凑的形式,你可以实现这样的扩展:

 扩展字符串{
func格式(参数:[CVarArgType]) - > String {
return String(format:self,arguments:arguments)
}
}

允许简化其使用,如下例所示:

 %d apples cost $%03.2f .format([4,4 * 0.33])


I am just starting to get to know Swift but I am having a serious problem with number formatting at an extremely basic level.

For example, I need to display an integer with at least 2 digits (e.g. 00, 01, 02, 03, 04, 05 ...). The normal syntax I'd expect would be something like:

println(" %02i %02i %02i", var1, var2, var3);

...but I don't find any clear instruction for how to achieve this in Swift. I find it really hard to believe that I need to create a custom function to do that. The same for returning a float or double value to a fixed number of decimal places.

I've found links to a couple of similar questions (Precision String Format Specifier In Swift & How to use println in Swift to format number) but they seem to mix objective C and even talk about Python and using unity libraries. Is there no Swift solution to this basic programming need? Is it really true that something so fundamental has been completely overlooked in Swift?

解决方案

You can construct a string with a c-like formatting using this constructor:

String(format: String, arguments:[CVarArgType])

Sample usage:

var x = 10

println(String(format: "%04d", arguments: [x])) // This will print "0010"

If you're going to use it a lot, and want a more compact form, you can implement an extension like this:

extension String {
    func format(arguments: [CVarArgType]) -> String {
        return String(format: self, arguments: arguments)
    }
}

allowing to simplify its usage as in this example:

"%d apples cost $%03.2f".format([4, 4 * 0.33])

这篇关于快速数字格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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