【问题标题】:Rounding Numbers to Two Significant Figures将数字四舍五入为两位有效数字
【发布时间】:2017-07-18 18:36:13
【问题描述】:

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

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

我知道 swift 有一个 .rounded() 函数,我已经设法使用它来舍入最接近的第 10 位、第 100 位等,但是,我无法按照我想要的方式进行舍入。任何建议将不胜感激。

【问题讨论】:

  • 这个例子是你想要的还是你得到的?您可以添加显示您尝试过的 Swift 代码吗?
  • 这是我想要的一个例子,对不起,我会编辑问题。
  • 你想要的是四舍五入到两位有效数字。如果结果应该是一个字符串,那么NumberFormatter 可以很容易地做到这一点。
  • 是的,谢谢,这个词让我忘记了,我将编辑问题的标题。我怎样才能四舍五入到两个无花果?

标签: swift rounding


【解决方案1】:

这是将任何Double 或Int(包括负数)四舍五入到给定有效数字位数的一种方法:

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

【讨论】:

  • 当 num 接近于零时,你会怎么做?应该有支票
【解决方案2】:

如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
}

【讨论】:

  • 假设你只想要一个字符串
  • @Kevin true,如果您希望 result 成为数字类型,则必须执行 Int(result)、Double(result) 等操作才能将其转换为您想要的类型
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 2012-09-09
    相关资源
    最近更新 更多