下面是我以前如何将一个浮点数截断到小数点后两位

NSLog(@" %.02f %.02f %.02f", r, g, b);

我查了文档和电子书,但还没找到答案。谢谢!


当前回答

import Foundation

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

使用

let offset = CGPoint(1.23, 4.56)
print("offset: \(offset.x.string1) x \(offset.y.string1)")
// offset: 1.2 x 4.6

其他回答

use

CGFloat 

or

Float.roundTo(places:2)

你仍然可以在Swift中使用NSLog,就像在Objective-C中一样,只是没有@符号。

NSLog("%.02f %.02f %.02f", r, g, b)

编辑:在与Swift合作一段时间后,我想添加这个变化

    var r=1.2
    var g=1.3
    var b=1.4
    NSLog("\(r) \(g) \(b)")

输出:

2014-12-07 21:00:42.128 MyApp[1626:60b] 1.2 1.3 1.4
//It will more help, by specify how much decimal Point you want.
let decimalPoint = 2
let floatAmount = 1.10001
let amountValue = String(format: "%0.*f", decimalPoint, floatAmount)

为什么要把它弄得这么复杂?你可以用这个代替:

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

看它在游乐场工作。

PS:解决方案来自:http://rrike.sh/xcode/rounding-various-decimal-places-swift/

一个更优雅和通用的解决方案是重写ruby / python %操作符:

// Updated for beta 5
func %(format:String, args:[CVarArgType]) -> String {
    return NSString(format:format, arguments:getVaList(args))
}

"Hello %@, This is pi : %.2f" % ["World", M_PI]