当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Swift FloatingPoint rounded(_:)用法及代码示例


实例方法

rounded(_:)

使用指定的舍入规则将此值返回为整数值。

必需的。提供默认实现。

声明

func rounded(_ rule: FloatingPointRoundingRule) -> Self

返回值

通过使用 rule 舍入找到的整数值。

参数

rule

要使用的舍入规则。

详述

以下示例使用四种不同的舍入规则对值进行舍入:


let x = 6.5


// Equivalent to the C 'round' function:
print(x.rounded(.toNearestOrAwayFromZero))
// Prints "7.0"


// Equivalent to the C 'trunc' function:
print(x.rounded(.towardZero))
// Prints "6.0"


// Equivalent to the C 'ceil' function:
print(x.rounded(.up))
// Prints "7.0"


// Equivalent to the C 'floor' function:
print(x.rounded(.down))
// Prints "6.0"

有关可用舍入规则的详细信息,请参阅FloatingPointRoundingRule 枚举。要使用默认 “schoolbook rounding” 对值进行舍入,您可以改用较短的 rounded() 方法。


print(x.rounded())
// Prints "7.0"

可用版本

iOS 8.0+, iPadOS 8.0+, macOS 10.10+, Mac Catalyst 13.0+, tvOS 9.0+, watchOS 2.0+

相关用法


注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 FloatingPoint rounded(_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。