truncatingRemainder vs remainder in Swift

后端 未结 2 1355
Happy的楠姐
Happy的楠姐 2021-02-08 05:53

Swift\'s substitutes for the % symbol for floating point numbers:


func truncatingRemainder(dividingBy other: Self) -> Self 
2条回答
  •  走了就别回头了
    2021-02-08 06:39

    This looks like a job for...playgrounds!

    let thing: Float = 8126.84652
    let truncating = thing.truncatingRemainder(dividingBy: 10) // value is 6.84668, analog to %
    let nonTruncating = thing.remainder(dividingBy: 10) // -3.15332
    

    As you can see, the plain remainder is allowed to go negative, (or rather, subtracts until the value is <=0) whereas the truncating remainder will remain positive. (stops when the value is >=0)

提交回复
热议问题