下面是我以前如何将一个浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查了文档和电子书,但还没找到答案。谢谢!
下面是我以前如何将一个浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查了文档和电子书,但还没找到答案。谢谢!
当前回答
为什么要把它弄得这么复杂?你可以用这个代替:
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/
其他回答
斯威夫特4
let string = String(format: "%.2f", locale: Locale.current, arguments: 15.123)
一个更优雅和通用的解决方案是重写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]
iOS 15+版本推荐:
2.31234.formatted(.number.precision(.fractionLength(1)))
Swift 4 Xcode 10更新
extension Double {
var asNumber:String {
if self >= 0 {
let formatter = NumberFormatter()
formatter.numberStyle = .none
formatter.percentSymbol = ""
formatter.maximumFractionDigits = 2
return "\(formatter.string(from: NSNumber(value: self)) ?? "")"
}
return ""
}
}
为什么要把它弄得这么复杂?你可以用这个代替:
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/