• 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 off numbers
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Rounding off numbers


  • Subject: Re: Rounding off numbers
  • From: James Bucanek <email@hidden>
  • Date: Sat, 10 Jun 2006 09:56:01 -0700

Johan Augustsson wrote on Saturday, June 10, 2006:

>Hi!
>
>I have a problem when I round of numbers. My first question is if
>there aren't any smother way to round off an NSNumber. I do it like
>this:
>
>myNbr is an NSNumber.
>NSNumber *myRoundedNbr=[NSNumber numberWithDouble:[[NSString
>stringWithFormat:@"%.2f", [myNbr floatValue]] doubleValue]];
>
>
>
>The bigger problem is that it doesn't round of correctly. Some tests
>show this:
>
>Nbr            Rounded
>2.265  =>  2.27        OK
>2.865  =>  2.87        OK
>2.965  =>  2.96        WRONG

From the man page for printf regarding %e and %f:

     Since the floating point numbers are translated from ASCII to floating-
     point and then back again, floating-point precision may be lost.

If you want a specific rounding, using the math functions to get the exactly that you want (i.e. don't rely on %f to do it for you -- and not to mention that it will be at least an order of magnitude more efficient):

    static NSNumber* sNumberRoundedToHundreds( float number )
    {
        return ([NSNumber numberWithFloat:roundf(number*100)/100]);
    }

--
James Bucanek
 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden

References: 
 >Rounding off numbers (From: Johan Augustsson <email@hidden>)

  • Prev by Date: Re: Rounding off numbers
  • Next by Date: Re: How to do an HTTP POST in Cocoa
  • Previous by thread: Re: Rounding off numbers
  • Next by thread: setAltIncrement on NSSlider
  • Index(es):
    • Date
    • Thread