Swift number formatting

元气小坏坏 提交于 2019-12-04 10:51:03

问题


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?


回答1:


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



回答2:


Here's a POP solution to the problem:

protocol Formattable {
    func format(pattern: String) -> String
}
extension Formattable where Self: CVarArg {
    func format(pattern: String) -> String {
        return String(format: pattern, arguments: [self])
    }
}
extension Int: Formattable { }
extension Double: Formattable { }
extension Float: Formattable { }

let myInt = 10
let myDouble: Double = 0.01
let myFloat: Float = 1.11

print(myInt.format(pattern: "%04d"))      // "0010
print(myDouble.format(pattern: "%.2f"))   // "0.01"
print(myFloat.format(pattern: "$%03.2f")) // "$1.11"
print(100.format(pattern: "%05d"))        // "00100"



回答3:


There is a simple solution I learned with "We <3 Swift", which is so easy you can even use without Foundation, round() or Strings, keeping the numeric value.

Example:

var number = 31.726354765
var intNumber = Int(number * 1000.0)
var roundedNumber = Double(intNumber) / 1000.0

result: 31.726




回答4:


You can still use good ole NSLog("%.2f",myFloatOrDouble) too :D



来源:https://stackoverflow.com/questions/26167453/swift-number-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!