Precision String Format Specifier In Swift

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

    A version of Vincent Guerci's ruby / python % operator, updated for Swift 2.1:

    func %(format:String, args:[CVarArgType]) -> String {
      return String(format:format, arguments:args)
    }
    
    "Hello %@, This is pi : %.2f" % ["World", M_PI]
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 06:23

    use

    CGFloat 
    

    or

    Float.roundTo(places:2)
    
    0 讨论(0)
  • 2020-11-22 06:24

    Swift 4

    let string = String(format: "%.2f", locale: Locale.current, arguments: 15.123)
    
    0 讨论(0)
  • 2020-11-22 06:24

    use below method

    let output = String.localizedStringWithFormat(" %.02f %.02f %.02f", r, g, b)
    
    println(output)
    
    0 讨论(0)
  • 2020-11-22 06:26

    Why make it so complicated? You can use this instead:

    import UIKit
    
    let PI = 3.14159265359
    
    round( PI ) // 3.0 rounded to the nearest decimal
    round( PI * 100 ) / 100 //3.14 rounded to the nearest hundredth
    round( PI * 1000 ) / 1000 // 3.142 rounded to the nearest thousandth
    

    See it work in Playground.

    PS: Solution from: http://rrike.sh/xcode/rounding-various-decimal-places-swift/

    0 讨论(0)
提交回复
热议问题