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
You can still use NSLog in Swift as in Objective-C just without the @ sign.
NSLog("%.02f %.02f %.02f", r, g, b)
Edit: After working with Swift since a while I would like to add also this variation
var r=1.2
var g=1.3
var b=1.4
NSLog("\(r) \(g) \(b)")
Output:
2014-12-07 21:00:42.128 MyApp[1626:60b] 1.2 1.3 1.4
a simple way is:
import Foundation // required for String(format: _, _)
print(String(format: "hex string: %X", 123456))
print(String(format: "a float number: %.5f", 1.0321))
This is a very fast and simple way who doesn't need complex solution.
let duration = String(format: "%.01f", 3.32323242)
// result = 3.3
extension Double {
func formatWithDecimalPlaces(decimalPlaces: Int) -> Double {
let formattedString = NSString(format: "%.\(decimalPlaces)f", self) as String
return Double(formattedString)!
}
}
1.3333.formatWithDecimalPlaces(2)
I found String.localizedStringWithFormat
to work quite well:
Example:
let value: Float = 0.33333
let unit: String = "mph"
yourUILabel.text = String.localizedStringWithFormat("%.2f %@", value, unit)
A more elegant and generic solution is to rewrite ruby / python %
operator:
// 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]