如何快速将 Double 舍入到最近的 Int?

时间:2023-03-29
本文介绍了如何快速将 Double 舍入到最近的 Int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个增长率计算器(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
}

但到目前为止我一直做不到.

but I've been unable so far.

编辑我是这样做的:

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 库中有一个round 可用(其实在Darwin,但是 Foundation 导入 Darwin 并且大多数时候你会想要使用 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() 总是在小数位为 >= .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, number of places)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):

四舍五入到小数点后两位:

Round to 2 decimal places:

let numberOfPlaces = 2.0
let multiplier = pow(10.0, numberOfPlaces)
let num = 10.12345
let rounded = round(num * multiplier) / multiplier
print(rounded)

输出:

10.12

注意:由于浮点数学的工作方式,rounded 可能并不总是完全准确.最好将其更多地考虑为舍入的近似值.如果您这样做是为了显示,最好使用字符串格式化来格式化数字,而不是使用数学来舍入它.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:整数总是初始化为0吗? 下一篇:如何在 Swift 中创建十六进制颜色字符串 UIColor 初

相关文章

最新文章