Swift-Tips之rounded(_:)

rounded(_:)

使用指定的舍入规则将该值取整。

代码示例

let nums = [3.0, 3.001, 3.5, 3.999, -3.0, -3.001, -3.5, -3.999]
let rules = [FloatingPointRoundingRule.awayFromZero, .down, .toNearestOrAwayFromZero, .toNearestOrEven, .towardZero, .up]

for rule in rules {
    print("========\(rule)========")
    for num in nums {
        let value = num.rounded(rule)
        print("Rule: \(rule), Source: \(num), Value: \(value)")
    }
}

/*
========awayFromZero========
Source: 3.0, Value: 3.0
Source: 3.001, Value: 4.0
Source: 3.5, Value: 4.0
Source: 3.999, Value: 4.0
Source: -3.0, Value: -3.0
Source: -3.001, Value: -4.0
Source: -3.5, Value: -4.0
Source: -3.999, Value: -4.0
========down========
Source: 3.0, Value: 3.0
Source: 3.001, Value: 3.0
Source: 3.5, Value: 3.0
Source: 3.999, Value: 3.0
Source: -3.0, Value: -3.0
Source: -3.001, Value: -4.0
Source: -3.5, Value: -4.0
Source: -3.999, Value: -4.0
========toNearestOrAwayFromZero========
Source: 3.0, Value: 3.0
Source: 3.001, Value: 3.0
Source: 3.5, Value: 4.0
Source: 3.999, Value: 4.0
Source: -3.0, Value: -3.0
Source: -3.001, Value: -3.0
Source: -3.5, Value: -4.0
Source: -3.999, Value: -4.0
========toNearestOrEven========
Source: 3.0, Value: 3.0
Source: 3.001, Value: 3.0
Source: 3.5, Value: 4.0
Source: 3.999, Value: 4.0
Source: -3.0, Value: -3.0
Source: -3.001, Value: -3.0
Source: -3.5, Value: -4.0
Source: -3.999, Value: -4.0
========towardZero========
Source: 3.0, Value: 3.0
Source: 3.001, Value: 3.0
Source: 3.5, Value: 3.0
Source: 3.999, Value: 3.0
Source: -3.0, Value: -3.0
Source: -3.001, Value: -3.0
Source: -3.5, Value: -3.0
Source: -3.999, Value: -3.0
========up========
Source: 3.0, Value: 3.0
Source: 3.001, Value: 4.0
Source: 3.5, Value: 4.0
Source: 3.999, Value: 4.0
Source: -3.0, Value: -3.0
Source: -3.001, Value: -3.0
Source: -3.5, Value: -3.0
Source: -3.999, Value: -3.0
 */

总结

  • awayFromZero: 四舍五入到最接近的值,返回值大于或等于源的大小(该规则比较的是绝对值)
let num = 3.5
num.rounded(.awayFromZero) // 4

let num2 = -3.5
num2.rounded(.awayFromZero) //-4
//可以看出 -4是小于-3.5的,所以它的规则说返回值大于或等于源指的是两值的绝对值的比较
  • down: 四舍五入到最接近的值,返回值小于于或等于源的大小(改规则不是比较的绝对值)
  • toNearestOrAwayFromZero: 四舍五入到最接近的值;如果两个值相等接近,则选择幅度较大的值
  • toNearestOrEven:四舍五入到最接近的值;如果两个值相等接近,则选择偶数。
let num = 3.5
// 这是3与4同等接近,选择偶数4
num.rounded(.toNearestOrEven)  // 4
let num2 = 4.5
// 这是4与5同等接近,选择偶数4
num2.rounded(.toNearestOrEven)  // 4
  • towardZero: 四舍五入到最接近的值,返回值小于于或等于源的大小;通过上面的例子可以看出它是忽略负号的;与awayFromZero对应
  • up: 四舍五入到最接近的值,返回值大于或等于源的大小;不忽略负号;与up对应

My Github

你可能感兴趣的:(Swift-Tips之rounded(_:))