• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: rounding a float
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: rounding a float


  • Subject: Re: rounding a float
  • From: Rainer Brockerhoff <email@hidden>
  • Date: Sun, 30 Nov 2003 18:30:58 -0200

>Date: Sun, 30 Nov 2003 12:56:56 -0500
>From: "Jay Rimalrick" <email@hidden>
>Reply-To: <email@hidden>
>To: <email@hidden>
>Subject: Re: rounding a float
>
>I am attempting write a function that take a float (inFloat) and returns a float
>(hopefully rounded for currency)
>
>Here is what I do inside my function:

If I may make a somewhat off-beat suggestion...

...unless you're an old-timer who's programmed for decades on 8/16 bit computers or mainframes where no floating point was available, somehow you think of using floating point for currency calculations. It's got a decimal point, so it's a float, right? No. Don't do it.

The best approach usually is to do what we did in those days. Make all calculations in cents in a long int (or long long int depending on the maximum value you need). This will round things automatically. Insert a decimal point manually when printing.

One other problem with floating point, besides the fact that 0.01 and most of its multiples have no exact floating point representation, is that adding thousands or millions of numbers may exceed the available bits in the mantissa very soon in the process, so you'll lose accuracy in the last places without noticing at all.


--
Rainer Brockerhoff <email@hidden>
Belo Horizonte, Brazil
"It's extremely unlucky to be superstitious, for no other reason
than it is always unlucky to be colossally stupid." (Stephen Fry)
Weblog: http://www.brockerhoff.net/bb/viewtopic.php
_______________________________________________
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.

  • Prev by Date: Re: rounding a float
  • Next by Date: newbie memory question
  • Previous by thread: Re: rounding a float
  • Next by thread: Eaves dropping on application events
  • Index(es):
    • Date
    • Thread