Swift中的舍入模式是否与Java中的ROUND_HALF_DOWN相同?
舍入模式向“最近邻居”舍入,除非两个邻居等距,在这种情况下向下舍入。如果丢弃的分数> 0.5,则表现为RoundingMode.UP;否则,表现为RoundingMode.DOWN。
例:
对于负数:
有 - 据我所知 - 没有与Java的FloatingPointRoundingRule
具有相同行为的ROUND_HALF_DOWN
,但你可以通过rounded()
和nextDown
或nextUp
的组合获得结果:
func roundHalfDown(_ x: Double) -> Double {
if x >= 0 {
return x.nextDown.rounded()
} else {
return x.nextUp.rounded()
}
}
例子:
print(roundHalfDown(2.4)) // 2.0
print(roundHalfDown(2.5)) // 2.0
print(roundHalfDown(2.6)) // 3.0
print(roundHalfDown(-2.4)) // -2.0
print(roundHalfDown(-2.5)) // -2.0
print(roundHalfDown(-2.6)) // -3.0
或者作为通用扩展方法,以便它可以与所有浮点类型(Float
,Double
,CGFloat
)一起使用:
extension FloatingPoint {
func roundedHalfDown() -> Self {
return self >= 0 ? nextDown.rounded() : nextUp.rounded()
}
}
例子:
print((2.4).roundedHalfDown()) // 2.0
print((2.5).roundedHalfDown()) // 2.0
print((2.6).roundedHalfDown()) // 3.0
print((-2.4).roundedHalfDown()) // -2.0
print((-2.5).roundedHalfDown()) // -2.0
print((-2.6).roundedHalfDown()) // -3.0
根据.round()
,Swift用规则实现Apple函数
case awayFromZero
舍入到最接近的允许值,其大小大于或等于源的大小。
case down
舍入到最接近的允许值,该值小于或等于源。
case toNearestOrAwayFromZero
舍入到最接近的允许值;如果两个值相等,则选择幅度更大的值。
case toNearestOrEven
舍入到最接近的允许值;如果两个值相等,则选择偶数。
case towardZero
舍入到最接近的允许值,其大小小于或等于源的大小。
case up
舍入到大于或等于源的最接近允许值。
var a = 6.54
a.round(.toNearestOrAwayFromZero)
// a == 7.0
var b = 6.54
b.round(.towardZero)
// b == 6.0
var c = 6.54
c.round(.up)
// c == 7.0
var d = 6.54
d.round(.down)
// d == 6.0
您也可以这样做,但也需要在小数点后取值。
正如@MohmmadS所说,这些是用于舍入的方法。
您可以像这样实现自定义舍入:
func round(_ value: Double, toNearest: Double) -> Double {
return round(value / toNearest) * toNearest
}
func roundDown(_ value: Double, toNearest: Double) -> Double {
return floor(value / toNearest) * toNearest
}
func roundUp(_ value: Double, toNearest: Double) -> Double {
return ceil(value / toNearest) * toNearest
}
例:
round(52.376, toNearest: 0.01) // 52.38
round(52.376, toNearest: 0.1) // 52.4
round(52.376, toNearest: 0.25) // 52.5
round(52.376, toNearest: 0.5) // 52.5
round(52.376, toNearest: 1) // 52