Round currency closest to five

只谈情不闲聊 提交于 2020-01-21 11:55:25

问题


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

Currently I'm doing it by getting the decimal values using:

let numbers = 5.33
let decimal = (numbers - rint(numbers)) * 100
let rounded = rint(numbers) + (5 * round(decimal / 5)) / 100

// This results in 5.35

I was wondering if there's a better method with fewer steps because sometimes numbers - rint(numbers) is giving me a weird result like:

let numbers = 12.12
let decimal = (numbers - rint(numbers)) * 100

// This results in 11.9999999999999

回答1:


Turns out..it's really simple

let x: Float = 1.03 //or whatever value, you can also use the Double type
let y = round(x * 20) / 20



回答2:


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



回答3:


I will use round function and NSNumberFormatter also but slightly different algorithm

I was thinking about using % but I changed it to /

let formatter = NSNumberFormatter()
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2

//5.30
formatter.stringFromNumber(round(5.31/0.05)*0.05)
//5.35
formatter.stringFromNumber(round(5.35/0.05)*0.05)
//5.35
formatter.stringFromNumber(round(5.33/0.05)*0.05)
//5.40
formatter.stringFromNumber(round(5.38/0.05)*0.05)
//12.15
formatter.stringFromNumber(round(12.13/0.05)*0.05)



回答4:


Depending on how you are storing your currency data, I would recommend using a dictionary or an array to look up the original cents value, and return a pre-computed result. There's no reason to do the calculations at all, since you know that 0 <= cents < 100.

If your currency is a string input, just chop off the last couple of digits and do a dictionary lookup.

round_cents = [ ... "12":"10", "13":"15", ... ]

If your currency is a floating point value, well, you have already discovered the joys of trying to do that. You should change it.

If your currency is a data type, or a fixed point integer, just get the cents part out and do an array lookup.

...
round_cents[12] = 10
round_cents[13] = 15
...

In either case, you would then do:

new_cents = round_cents[old_cents]

and be done with it.



来源:https://stackoverflow.com/questions/35613696/round-currency-closest-to-five

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!