Swift 双圆到最接近的10
我想将一个Swift 双圆到最接近的10,swift,math,rounding,Swift,Math,Rounding,我想将一个Double四舍五入到10的最接近倍数 例如,如果数字为8.0,则四舍五入为10。 如果数字为2.0,则将其四舍五入为0 我该怎么做呢?您可以使用round()函数(对浮点数进行舍入) 并应用10的“比例因子”: 用法示例: print(roundToTens(4.9)) // 0 print(roundToTens(15.1)) // 20 在第二个示例中,15.1除以10(1.51),四舍五入(2.0), 转换为整数(2)并再次乘以10(20) Swift 3: func ro
Double
四舍五入到10的最接近倍数
例如,如果数字为8.0,则四舍五入为10。
如果数字为2.0,则将其四舍五入为0
我该怎么做呢?您可以使用
round()
函数(对浮点数进行舍入)
并应用10的“比例因子”:
用法示例:
print(roundToTens(4.9)) // 0
print(roundToTens(15.1)) // 20
在第二个示例中,15.1
除以10(1.51
),四舍五入(2.0
),
转换为整数(2
)并再次乘以10(20
)
Swift 3:
func roundToTens(_ x : Double) -> Int {
return 10 * Int((x / 10.0).rounded())
}
或者:
func roundToTens(_ x : Double) -> Int {
return 10 * lrint(x / 10.0)
}
在Swift 3.0中,它是
10 * Int(round(Double(ratio / 10)))
swift中BinaryFloatingPoint的出色扩展:
extension BinaryFloatingPoint{
func roundToTens() -> Int{
return 10 * Int(Darwin.round(self / 10.0))
}
func roundToHundreds() -> Int{
return 100 * Int(Darwin.round(self / 100.0))
}
}
将舍入函数定义为
import Foundation
func round(_ value: Double, toNearest: Double) -> Double {
return round(value / toNearest) * toNearest
}
为您提供了更通用、更灵活的方法
let r0 = round(1.27, toNearest: 0.25) // 1.25
let r1 = round(325, toNearest: 10) // 330.0
let r3 = round(.pi, toNearest: 0.0001) // 3.1416
您还可以扩展
FloatingPoint
协议,并添加一个选项来选择舍入规则:
extension FloatingPoint {
func rounded(to value: Self, roundingRule: FloatingPointRoundingRule = .toNearestOrAwayFromZero) -> Self {
(self / value).rounded(roundingRule) * value
}
}
四舍五入到任意数字的扩展
extension Int{
func rounding(nearest:Float) -> Int{
return Int(nearest * round(Float(self)/nearest))
}
}
用法:
36roundToTens
10*Int(round(Double((325)/10))
给我320。如果介于两者之间,如何获得330?这是一个很好的一般性答案,与现有的round()方法一致。应该有更多的向上投票。extension BinaryFloatingPoint{func roundToTens()->Self{return(Self/10)。rounded()*10}
let value = 325.0
value.rounded(to: 10) // 330 (default rounding mode toNearestOrAwayFromZero)
value.rounded(to: 10, roundingRule: .down) // 320
extension Int{
func rounding(nearest:Float) -> Int{
return Int(nearest * round(Float(self)/nearest))
}
}
extension Double {
var roundToTens: Double {
let divideByTen = self / 10
let multiByTen = (ceil(divideByTen) * 10)
return multiByTen
}
}