Precision String Format Specifier In Swift

前端 未结 30 2086
面向向阳花
面向向阳花 2020-11-22 05:58

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 an

30条回答
  •  失恋的感觉
    2020-11-22 06:13

    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.

提交回复
热议问题