Precision String Format Specifier In Swift

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

    You can't do it (yet) with string interpolation. Your best bet is still going to be NSString formatting:

    println(NSString(format:"%.2f", sqrt(2.0)))
    

    Extrapolating from python, it seems like a reasonable syntax might be:

    @infix func % (value:Double, format:String) -> String {
        return NSString(format:format, value)
    }
    

    Which then allows you to use them as:

    M_PI % "%5.3f"                // "3.142"
    

    You can define similar operators for all of the numeric types, unfortunately I haven't found a way to do it with generics.

    Swift 5 Update

    As of at least Swift 5, String directly supports the format: initializer, so there's no need to use NSString and the @infix attribute is no longer needed which means the samples above should be written as:

    println(String(format:"%.2f", sqrt(2.0)))
    
    func %(value:Double, format:String) -> String {
        return String(format:format, value)
    }
    
    Double.pi % "%5.3f"         // "3.142"
    

提交回复
热议问题