谁能告诉我如何在Swift中舍入一个双数值到x位小数点后数位?
我有:
var totalWorkTimeInHours = (totalWorkTime/60/60)
totalWorkTime是一个NSTimeInterval (double),单位为秒。
totalWorkTimeInHours会给我小时数,但它给我的时间量是如此长的精确数字,例如1.543240952039......
当我打印totalWorkTimeInHours时,我如何将其四舍五入到1.543 ?
谁能告诉我如何在Swift中舍入一个双数值到x位小数点后数位?
我有:
var totalWorkTimeInHours = (totalWorkTime/60/60)
totalWorkTime是一个NSTimeInterval (double),单位为秒。
totalWorkTimeInHours会给我小时数,但它给我的时间量是如此长的精确数字,例如1.543240952039......
当我打印totalWorkTimeInHours时,我如何将其四舍五入到1.543 ?
当前回答
Lots of example are using maths, the problem is floats are approximations of real number, there is no way to express 0.1 (1/10) exactly as a float just as there is no exact way to express ⅓ exactly using decimal points, so you need to ask your self exactly what your are trying to achieve, if you just want to display them leave them as they are in code, trying to round them is going to justify give you less accurate result as you are throwing away precious, round ⅓ in decimal notation to 1 decimal place is not going to give you a number closer to ⅓, us NumberFormate to round it, if you have something like a viewModel class it can be used to return a string representation to your models numbers. NumberFormaters give you lots of control on how numbers are formatted and the number of decimal places you want.
其他回答
如果你想在逗号后面只有0表示圆,试试这个:
extension Double {
func isInteger() -> Any {
let check = floor(self) == self
if check {
return Int(self)
} else {
return self
}
}
}
let toInt: Double = 10.0
let stillDouble: Double = 9.12
print(toInt.isInteger) // 10
print(stillDouble.isInteger) // 9.12
当我打印totalWorkTimeInHours时,我如何将其四舍五入到1.543 ?
要将totalWorkTimeInHours四舍五入为3位数字以便打印,使用String构造函数,它接受一个格式字符串:
print(String(format: "%.3f", totalWorkTimeInHours))
Swift最佳方式
这就是我把四舍五入到小数点后两位的方法
let val = round(100 * scale) / 100
不是斯威夫特,但我相信你明白我的意思。
pow10np = pow(10,num_places);
val = round(val*pow10np) / pow10np;
这在Swift 5中似乎有效。
令人惊讶的是,现在还没有这样的标准函数。
//用四舍五入截断双位数到小数点后n位
extension Double {
func truncate(to places: Int) -> Double {
return Double(Int((pow(10, Double(places)) * self).rounded())) / pow(10, Double(places))
}
}