Swift number formatting

前端 未结 4 1097
深忆病人
深忆病人 2021-02-08 08:10

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 w

4条回答
  •  悲&欢浪女
    2021-02-08 08:41

    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])
    

提交回复
热议问题