1. 程式人生 > >Swift-Tips之rounded(_:)

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