下面是我以前如何将一个浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查了文档和电子书,但还没找到答案。谢谢!
下面是我以前如何将一个浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查了文档和电子书,但还没找到答案。谢谢!
当前回答
这是一种非常快速和简单的方法,不需要复杂的解决方案。
let duration = String(format: "%.01f", 3.32323242)
// result = 3.3
其他回答
使用以下方法
let output = String.localizedStringWithFormat(" %.02f %.02f %.02f", r, g, b)
println(output)
为什么要把它弄得这么复杂?你可以用这个代替:
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/
Vincent Guerci的ruby / python %操作符,为Swift 2.1更新:
func %(format:String, args:[CVarArgType]) -> String {
return String(format:format, arguments:args)
}
"Hello %@, This is pi : %.2f" % ["World", M_PI]
Swift2示例:iOS设备的屏幕宽度格式化浮点数去除小数
print(NSString(format: "Screen width = %.0f pixels", CGRectGetWidth(self.view.frame)))
那么Double和CGFloat类型的扩展呢?
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)"
}
}
}
用法:
let aNumber: Double = 112465848348508.458758344
Swift.print("The number: \(aNumber.formatted(2))")
打印:112 465 848 348 508.46