Re: rounding a float
Re: rounding a float
- Subject: Re: rounding a float
- From: Alastair Houghton <email@hidden>
- Date: Sun, 30 Nov 2003 11:50:27 +0000
On 30 Nov 2003, at 00:17, Jay Rimalrick wrote:
>
What is the easiest way to round a float value with either c or
>
objective-c. I
>
need this float value to be consistent with the rounding of currency
>
e.g.
>
1.255 rounds to 1.26 and
>
1.254 rounds to 1.25
Don't use a floating-point value (in fact, I'd go as far as to say that
you should *never* use floating-point for currency values). Use an
integer and scale it appropriately... e.g. for three digits of
precision, you'd use a scale factor of 1,000; then rounding becomes
fairly easy:
1.255 => 1,255
1.254 => 1,254
To round, add 5, then subtract n % 10:
1,255 + 5 = 1,260
1,260 % 10 = 0
Subtract the two, we get 1,260 (equivalent to 1.26)
1,254 + 5 = 1,259
1,259 % 10 = 9
Subtract the two, we get 1,250 (equivalent to 1.25)
The only time you need to watch what you're at is when multiplying or
dividing two currencies, but that doesn't happen very often as it
doesn't usually make sense... mostly you just add and subtract them.
Kind regards,
Alastair.
[demime 0.98b removed an attachment of type application/pkcs7-signature which had a name of smime.p7s]
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.