Precision String Format Specifier In Swift

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

    What about extensions on Double and CGFloat types:

    extension Double {
    
       func formatted(_ decimalPlaces: Int?) -> String {
          let theDecimalPlaces : Int
          if decimalPlaces != nil {
             theDecimalPlaces = decimalPlaces!
          }
          else {
             theDecimalPlaces = 2
          }
          let theNumberFormatter = NumberFormatter()
          theNumberFormatter.formatterBehavior = .behavior10_4
          theNumberFormatter.minimumIntegerDigits = 1
          theNumberFormatter.minimumFractionDigits = 1
          theNumberFormatter.maximumFractionDigits = theDecimalPlaces
          theNumberFormatter.usesGroupingSeparator = true
          theNumberFormatter.groupingSeparator = " "
          theNumberFormatter.groupingSize = 3
    
          if let theResult = theNumberFormatter.string(from: NSNumber(value:self)) {
             return theResult
          }
          else {
             return "\(self)"
          }
       }
    }
    

    Usage:

    let aNumber: Double = 112465848348508.458758344
    Swift.print("The number: \(aNumber.formatted(2))")
    

    prints: 112 465 848 348 508.46

提交回复
热议问题