如何将Double转换成最接近的Int? [英] How to round a Double to the nearest Int in swift?
问题描述
我正在尝试制作增长率计算器( Double
),将结果舍入到最近的整数,并从那里重新计算,如下所示:
I'm trying to make a calculator of growth rate (Double
) that will round the result to the nearest Integer and recalculate from there, as such:
let firstUsers = 10.0
let growth = 0.1
var users = firstUsers
var week = 0
while users < 14 {
println("week \(week) has \(users) users")
users += users * growth
week += 1
}
但我一直无法实现。
我有点像这样:
EDIT I kinda did it like so:
var firstUsers = 10.0
let growth = 0.1
var users:Int = Int(firstUsers)
var week = 0
while users <= 14 {
println("week \(week) has \(users) users")
firstUsers += firstUsers * growth
users = Int(firstUsers)
week += 1
}
虽然我不介意它总是四舍五入,我不喜欢它,因为 firstUsers
必须成为一个变量,并在整个程序中进行更改(为了进行下一个计算),我不希望它发生。
Although I don't mind that it is always rounding down, I don't like it because firstUsers
had to become a variable and change throughout the program (in order to make the next calculation), which I don't want it to happen.
推荐答案
在 Foundation $ c $中有一个
圆
c> library (这是实际上在达尔文
,但基金会
进口达尔文
和大部分您将需要使用 Foundation
而不是直接使用 Darwin
。
There is a round
available in the Foundation
library (it's actually in Darwin
, but Foundation
imports Darwin
and most of the time you'll want to use Foundation
instead of using Darwin
directly).
import Foundation
users = round(users)
在操场上运行代码,然后调用:
Running your code in a playground and then calling:
print(round(users))
输出:
15.0
round()
always当小数点位于> = .5
时舍入,当它 < .5
(标准舍入)。您可以使用 floor()
强制舍入,而 ceil()
强制四舍五入。
round()
always rounds up when the decimal place is >= .5
and down when it's < .5
(standard rounding). You can use floor()
to force rounding down, and ceil()
to force rounding up.
如果你需要到特定的地方,那么你乘以 pow(10.0,地点数)
, round
,然后除以 pow(10,地点数)
:
If you need to round to a specific place, then you multiply by pow(10.0, number of places)
, round
, and then divide by pow(10, number of places)
:
舍入到小数点后两位:
let numberOfPlaces = 2.0
let multiplier = pow(10.0, numberOfPlaces)
let num = 10.12345
let rounded = round(10.12345 * multiplier) / multiplier
print(rounded)
输出:
10.12
10.12
注意由于浮点数学运算的方式,四舍五入
可能不总是完全准确。最好是考虑一下近似的四舍五入。如果你这样做是为了显示目的,最好使用字符串格式来格式化数字,而不是使用数学来舍弃它。
Note: Due to the way floating point math works, rounded
may not always be perfectly accurate. It's best to think of it more of an approximation of rounding. If you're doing this for display purposes, it's better to use string formatting to format the number rather than using math to round it.
这篇关于如何将Double转换成最接近的Int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!