Precision String Format Specifier In Swift

2018-12-31 08:29发布

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 and the eBook but haven't been able to figure it out. Thanks!

标签: swift
29条回答
梦醉为红颜
2楼-- · 2018-12-31 09:08

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/

查看更多
弹指情弦暗扣
3楼-- · 2018-12-31 09:09
import Foundation

extension CGFloat {
    var string1: String {
        return String(format: "%.1f", self)
    }
    var string2: String {
        return String(format: "%.2f", self)
    }
}

Usage

let offset = CGPoint(1.23, 4.56)
print("offset: \(offset.x.string1) x \(offset.y.string1)")
// offset: 1.2 x 4.6
查看更多
路过你的时光
4楼-- · 2018-12-31 09:10
extension Double {
  func formatWithDecimalPlaces(decimalPlaces: Int) -> Double {
     let formattedString = NSString(format: "%.\(decimalPlaces)f", self) as String
     return Double(formattedString)!
     }
 }

 1.3333.formatWithDecimalPlaces(2)
查看更多
闭嘴吧你
5楼-- · 2018-12-31 09:10

The answers given so far that have received the most votes are relying on NSString methods and are going to require that you have imported Foundation.

Having done that, though, you still have access to NSLog.

So I think the answer to the question, if you are asking how to continue using NSLog in Swift, is simply:

import Foundation

查看更多
萌妹纸的霸气范
6楼-- · 2018-12-31 09:10

less typing way:

func fprint(format: String, _ args: CVarArgType...) {
    print(NSString(format: format, arguments: getVaList(args)))
}
查看更多
登录 后发表回答