Precision String Format Specifier In Swift

2018-12-31 08:29发布

Below is how I would have previously truncated a float to two decimal places

NSLog(@" %.02f %.02f %.02f", r, g, b);

I checked the docs and the eBook but haven't been able to figure it out. Thanks!

标签: swift
29条回答
琉璃瓶的回忆
2楼-- · 2018-12-31 08:45

Swift 4

let string = String(format: "%.2f", locale: Locale.current, arguments: 15.123)
查看更多
余生请多指教
3楼-- · 2018-12-31 08:46

I don't know about two decimal places, but here's how you can print floats with zero decimal places, so I'd imagine that can be 2 place, 3, places ... (Note: you must convert CGFloat to Double to pass to String(format:) or it will see a value of zero)

func logRect(r: CGRect, _ title: String = "") {
    println(String(format: "[ (%.0f, %.0f), (%.0f, %.0f) ] %@",
        Double(r.origin.x), Double(r.origin.y), Double(r.size.width), Double(r.size.height), title))
}
查看更多
不再属于我。
4楼-- · 2018-12-31 08:48

This is a very fast and simple way who doesn't need complex solution.

let duration = String(format: "%.01f", 3.32323242)
// result = 3.3
查看更多
谁念西风独自凉
5楼-- · 2018-12-31 08:49

Plenty of good answers above, but sometimes a pattern is more appropriate than the "%.3f" sort of gobbledygook. Here's my take using a NumberFormatter in Swift 3.

extension Double {
  func format(_ pattern: String) -> String {
    let formatter = NumberFormatter()
    formatter.format = pattern
    return formatter.string(from: NSNumber(value: self))!
  }    
}

let n1 = 0.350, n2 = 0.355
print(n1.format("0.00#")) // 0.35
print(n2.format("0.00#")) // 0.355

Here I wanted 2 decimals to be always shown, but the third only if it wasn't zero.

查看更多
初与友歌
6楼-- · 2018-12-31 08:50

You can still use NSLog in Swift as in Objective-C just without the @ sign.

NSLog("%.02f %.02f %.02f", r, g, b)

Edit: After working with Swift since a while I would like to add also this variation

    var r=1.2
    var g=1.3
    var b=1.4
    NSLog("\(r) \(g) \(b)")

Output:

2014-12-07 21:00:42.128 MyApp[1626:60b] 1.2 1.3 1.4
查看更多
长期被迫恋爱
7楼-- · 2018-12-31 08:50

You can also create an operator in this way

operator infix <- {}

func <- (format: String, args:[CVarArg]) -> String {
    return String(format: format, arguments: args)
}

let str = "%d %.1f" <- [1453, 1.123]
查看更多
登录 后发表回答