下面是我以前如何将一个浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查了文档和电子书,但还没找到答案。谢谢!
下面是我以前如何将一个浮点数截断到小数点后两位
NSLog(@" %.02f %.02f %.02f", r, g, b);
我查了文档和电子书,但还没找到答案。谢谢!
当前回答
@Christian Dietrich):
而不是:
var k = 1.0
for i in 1...right+1 {
k = 10.0 * k
}
let n = Double(Int(left*k)) / Double(k)
return "\(n)"
也可以是:
let k = pow(10.0, Double(right))
let n = Double(Int(left*k)) / k
return "\(n)"
(更正:) 抱歉混淆* -当然这适用于双打。我认为,最实用的(如果你想让数字四舍五入,而不是被切断)应该是这样的:
infix operator ~> {}
func ~> (left: Double, right: Int) -> Double {
if right <= 0 {
return round(left)
}
let k = pow(10.0, Double(right))
return round(left*k) / k
}
仅对于Float,只需将Double替换为Float, pow替换为powf, round替换为roundf。 更新:我发现它是最实用的使用返回类型Double而不是字符串。它的工作原理与字符串输出相同,即:
println("Pi is roughly \(3.1415926 ~> 3)")
印花:圆周率大约是3.142 所以你可以用同样的方式使用它的字符串(你甚至可以写:println(d ~> 2)),但另外你也可以用它直接舍入值,即:
d = Double(slider.value) ~> 2
或者任何你需要的…
其他回答
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]
那么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
Swift2示例:iOS设备的屏幕宽度格式化浮点数去除小数
print(NSString(format: "Screen width = %.0f pixels", CGRectGetWidth(self.view.frame)))
你还不能用字符串插值来做。你最好的选择仍然是NSString格式化:
println(NSString(format:"%.2f", sqrt(2.0)))
从python中推断,合理的语法可能是:
@infix func % (value:Double, format:String) -> String {
return NSString(format:format, value)
}
然后允许你使用它们作为:
M_PI % "%5.3f" // "3.142"
你可以为所有的数字类型定义类似的操作符,不幸的是我还没有找到一种方法来使用泛型。
Swift 5更新
至少在Swift 5中,String直接支持format: initializer,所以不需要使用NSString, @infix属性也不再需要,这意味着上面的示例应该写成:
println(String(format:"%.2f", sqrt(2.0)))
func %(value:Double, format:String) -> String {
return String(format:format, value)
}
Double.pi % "%5.3f" // "3.142"
use
CGFloat
or
Float.roundTo(places:2)