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

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

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


当前回答

到目前为止,得到最多投票的答案依赖于NSString方法,并且需要你导入Foundation。

完成这些之后,你仍然可以访问NSLog。

所以我认为这个问题的答案,如果你在问如何继续在Swift中使用NSLog,很简单:

进口的基础

其他回答

到目前为止,得到最多投票的答案依赖于NSString方法,并且需要你导入Foundation。

完成这些之后,你仍然可以访问NSLog。

所以我认为这个问题的答案,如果你在问如何继续在Swift中使用NSLog,很简单:

进口的基础

您也可以用这种方式创建操作符

operator infix <- {}

func <- (format: String, args:[CVarArg]) -> String {
    return String(format: format, arguments: args)
}

let str = "%d %.1f" <- [1453, 1.123]
//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)

iOS 15+版本推荐:

2.31234.formatted(.number.precision(.fractionLength(1)))

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

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/