Round currency closest to five

后端 未结 4 931
庸人自扰
庸人自扰 2021-01-19 05:19

I\'d like to round my values to the closest of 5 cent for example:

5.31 -> 5.30
5.35 -> 5.35
5.33 -> 5.35
5.38 -> 5.40

Currentl

4条回答
  •  清歌不尽
    2021-01-19 05:57

    It's really better to stay away from floating-point for this kind of thing, but you can probably improve the accuracy a little with this:

    import Foundation
    
    func roundToFive(n: Double) -> Double {
      let f = floor(n)
      return f + round((n-f) * 20) / 20
    }
    
    roundToFive(12.12) // 12.1
    

提交回复
热议问题