舍入数字到两个重要数字

时间:2017-07-18 18:36:13

标签: swift rounding

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

12.6 //Want rounded to 13
126 //Want rounded to 130
1264 //Want rounded to 1300

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

3 个答案:

答案 0 :(得分: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))

输出:

  

0.27
  1.3
  13.0
  130个
  1300

答案 1 :(得分:2)

实现舍入算法的一种可能性。我想你总是希望结果是整数。

func round(_ number: Float, to digits: Int) -> Float {
    guard number >= 0 else {
        return -round(-number, to: digits)
    }

    let max = pow(10, Float(digits))

    var numZeros = 0
    var value = number

    while (value >= max) {
        value /= 10
        numZeros += 1
    }

    return round(value) * pow(10, Float(numZeros))
}

print(round(12.6, to: 2)) // 13
print(round(126, to: 2))  // 130
print(round(1264, to: 2)) // 1300

答案 2 :(得分:1)

正如Sulthan所述,您可以使用NumberFormatter

let formatter = NumberFormatter()

formatter.usesSignificantDigits = true
formatter.maximumSignificantDigits = 2
formatter.minimumSignificantDigits = 2

if let result = formatter.string(from: 12.6) {
    print(result)  // prints 13
}