views:

194

answers:

3

How to round a number to end in 50 in obj c or c++ / cocoa?

I am writing a tax program, for the final lookup i have to round the income to end in 50 before i apply the tax rate.

The only alternative i can think of is string modification, but im shaky in that area,].

+5  A: 

It's unclear whether you want the nearest $50 or 50 cents, so here's both:

For an integer to go to a multiple of 50, you need the formula:

x = int(x / 50) * 50               ; for truncation.
x = int((x + 25) / 50) * 50        ; for rounding.

For an float to go to a multiple of 0.50, you need the formula:

x = 0.5 * int(x / 0.5)             ; for truncation.
x = 0.5 * int((x + 0.25) / 0.5)    ; for rounding.

Update:

If you just want the last two digits changed to 50, simply do one of:

x = x - (x % 100) + 50
x = 50 + 100 * int (x / 100)
paxdiablo
Not that you should use floating-point for money…
Peter Hosey
Floats are fine if you understand their behavior (no wildly disparate exponents, not too much adding and even less multiplication because of cumulative errors), but you're right. To be absolutely safe, you should be using scaled integers or decimal classes of some sort.
paxdiablo
Thanks, the rounding works well. I should of been more clear, i need the number to end in "50" the last 2 digits have to be changed to 50. Thats why i was afraid that ill have to to some string stuff, id like to keep it in c++ / objc and avoid cocoa
@james, that's even easier. See the update.
paxdiablo
I have to disagree w/ Peter- floating point should not be used for currency calculations, especially in a tax app.
sbooth
@sbooth, I think you misunderstood @Peter, he said "Not that you should...", not "Note that you should...". He's against the idea of floats for money.
paxdiablo
Thanks, i have done modulias in algebra class before and programming class, the whole thing just didn't come to me. (smacks head)
+2  A: 
x-=x%50; /*for truncating*/
ammoQ
A: 

Give a man a fish and he has food for one day.

What you want to know is how many 'chunks' of 50 are in a number. This can be achieved by floating point division.

const double chunksize = 50.;
const double chunks=income/chunksize;

Then, apparently, you get to an integer number of chunks, by rounding, truncating, ...

const int i_chunks = ceil( chunks );

And finally you want to scale the number of chunks back to the original currency:

const double chunked_income = i_chunks*chunksize;
xtofl
"Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life." - Terry Pratchett :-)
paxdiablo