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
对应
以上所述就是小编给大家介绍的《Swift-Tips之rounded(_:)》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。