Precision String Format Specifier In Swift

前端 未结 30 2045
面向向阳花
面向向阳花 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:27

    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
    
    0 讨论(0)
  • 2020-11-22 06:31

    a simple way is:

    import Foundation // required for String(format: _, _)
    
    print(String(format: "hex string: %X", 123456))
    print(String(format: "a float number: %.5f", 1.0321))
    
    0 讨论(0)
  • 2020-11-22 06:31

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

    let duration = String(format: "%.01f", 3.32323242)
    // result = 3.3
    
    0 讨论(0)
  • 2020-11-22 06:33
    extension Double {
      func formatWithDecimalPlaces(decimalPlaces: Int) -> Double {
         let formattedString = NSString(format: "%.\(decimalPlaces)f", self) as String
         return Double(formattedString)!
         }
     }
    
     1.3333.formatWithDecimalPlaces(2)
    
    0 讨论(0)
  • 2020-11-22 06:34

    I found String.localizedStringWithFormat to work quite well:

    Example:

    let value: Float = 0.33333
    let unit: String = "mph"
    
    yourUILabel.text = String.localizedStringWithFormat("%.2f %@", value, unit)
    
    0 讨论(0)
  • 2020-11-22 06:34

    A more elegant and generic solution is to rewrite ruby / python % operator:

    // Updated for beta 5
    func %(format:String, args:[CVarArgType]) -> String {
        return NSString(format:format, arguments:getVaList(args))
    }
    
    "Hello %@, This is pi : %.2f" % ["World", M_PI]
    
    0 讨论(0)
提交回复
热议问题