Precision String Format Specifier In Swift

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

提交回复
热议问题