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

Re: Formatting float numbers


  • Subject: Re: Formatting float numbers
  • From: Greg Parker <email@hidden>
  • Date: Sun, 22 Aug 2010 15:04:47 -0700

On Aug 21, 2010, at 9:59 AM, Adriano Brandão wrote:
> I'm having some troubles in formatting float numbers. If I wish to display 25.342 using only 2 decimal places I could use %.2f and it would do the job. But if the number to be formatted is flat (like 25.000) I get 25.00 as a result.
> After a little bit of research I found out that I could use # as a flag (%.#2f). But, even in this case, I get 25. (with the dot). So, what's the right way for displaying only 25 (mantaining the 2 decimal places for numbers that use them)?

You can't get that result directly from printf(3), but you can do it with NSNumberFormatter:

    {
        NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];
        [fmt setFormat:@"0.##"];
        NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);
        NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.3]]);
        NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.0]]);
    }

    2010-08-22 15:04:10.614 a.out[6954:903] 25.34
    2010-08-22 15:04:10.616 a.out[6954:903] 25.3
    2010-08-22 15:04:10.617 a.out[6954:903] 25


--
Greg Parker     email@hidden     Runtime Wrangler


_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden

  • Follow-Ups:
    • Re: Formatting float numbers
      • From: Adriano Brandão <email@hidden>
References: 
 >Formatting float numbers (From: Adriano Brandão <email@hidden>)

  • Prev by Date: Re: Core Data Lightweight Migration Woes
  • Next by Date: NSArrayController + KVO + Core Data Question
  • Previous by thread: Formatting float numbers
  • Next by thread: Re: Formatting float numbers
  • Index(es):
    • Date
    • Thread