本文翻译自:Rounding a double value to x number of decimal places in swift
Can anyone tell me how to round a double value to x number of decimal places in Swift? 谁能告诉我在Swift中如何将双精度值四舍五入到小数点后位数x?
I have: 我有:
var totalWorkTimeInHours = (totalWorkTime/60/60)
With totalWorkTime
being an NSTimeInterval (double) in second. totalWorkTime
是NSTimeInterval(双精度),以秒为单位。
totalWorkTimeInHours
will give me the hours, but it gives me the amount of time in such a long precise number eg 1.543240952039...... totalWorkTimeInHours
将给我小时,但是它给了我这么长的精确时间,例如1.543240952039 ......
How do I round this down to, say, 1.543 when I print totalWorkTimeInHours
? 在打印totalWorkTimeInHours
时如何将其四舍五入为1.543?
#1楼
参考:https://stackoom.com/question/1qi0j/快速将双精度值四舍五入到x小数位数
#2楼
Not Swift but I'm sure you get the idea. 不是Swift,但是我敢肯定,您会明白的。
pow10np = pow(10,num_places);
val = round(val*pow10np) / pow10np;
#3楼
How do I round this down to, say, 1.543 when I print
totalWorkTimeInHours
? 在打印totalWorkTimeInHours
时如何将其四舍五入为1.543?
To round totalWorkTimeInHours
to 3 digits for printing, use the String
constructor which takes a format
string: 要将totalWorkTimeInHours
舍totalWorkTimeInHours
为3位以进行打印,请使用String
构造函数,该构造函数采用format
字符串:
print(String(format: "%.3f", totalWorkTimeInHours))
#4楼
You can use Swift's round
function to accomplish this. 您可以使用Swift的round
函数来完成此操作。
To round a Double
with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000: 要以3位精度四舍五入一个Double
,请先将其乘以1000,四舍五入,然后将四舍五入的结果除以1000:
let x = 1.23556789
let y = Double(round(1000*x)/1000)
print(y) // 1.236
Other than any kind of printf(...)
or String(format: ...)
solutions, the result of this operation is still of type Double
. 除了任何类型的printf(...)
或String(format: ...)
解决方案之外,此操作的结果仍为Double
类型。
EDIT: 编辑:
Regarding the comments that it sometimes does not work, please read this: 关于有时无效的评论,请阅读以下内容:
What Every Computer Scientist Should Know About Floating-Point Arithmetic 每个计算机科学家都应了解的浮点运算法则
#5楼
Building on Yogi's answer, here's a Swift function that does the job: 在Yogi的答案的基础上,这是完成任务的Swift函数:
func roundToPlaces(value:Double, places:Int) -> Double {
let divisor = pow(10.0, Double(places))
return round(value * divisor) / divisor
}
#6楼
A handy way can be the use of extension of type Double 一种方便的方法是使用Double类型的扩展名
extension Double {
var roundTo2f: Double {return Double(round(100 *self)/100) }
var roundTo3f: Double {return Double(round(1000*self)/1000) }
}
Usage: 用法:
let regularPie: Double = 3.14159
var smallerPie: Double = regularPie.roundTo3f // results 3.142
var smallestPie: Double = regularPie.roundTo2f // results 3.14