舍入数字到两个重要数字

M.I*_*M.I 4 rounding swift

我相信对于你们在Swift中经验丰富的人来说这是一个简单的问题,但是,我刚开始学习如何编程并且不知道从哪里开始.我想要做的是将数字舍入到最接近的整数或第三个数字.这就是我的意思:

12.6 //Want rounded to 13
126 //Want rounded to 130
1264 //Want rounded to 1300
Run Code Online (Sandbox Code Playgroud)

我知道斯威夫特有一个.rounded()功能,我已经设法使用它来绕近最近的第10,100等,但是,我不能绕过我想要的方式.任何建议将不胜感激.

rma*_*ddy 8

这是将任意DoubleInt(包括负数)舍入到给定数量的有效数字的一种方法:

func round(_ num: Double, to places: Int) -> Double {
    let p = log10(abs(num))
    let f = pow(10, p.rounded() - Double(places) + 1)
    let rnum = (num / f).rounded() * f

    return rnum
}

func round(_ num: Int, to places: Int) -> Int {
    let p = log10(abs(Double(num)))
    let f = pow(10, p.rounded() - Double(places) + 1)
    let rnum = (Double(num) / f).rounded() * f

    return Int(rnum)
}

print(round(0.265, to: 2))
print(round(1.26, to: 2))
print(round(12.6, to: 2))
print(round(126, to: 2))
print(round(1264, to: 2))
Run Code Online (Sandbox Code Playgroud)

输出:

0.27
1.3
13.0
130
1300