• 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: Howard Hinnant <email@hidden>
  • Date: Sat, 21 Aug 2010 14:07:05 -0400

On Aug 21, 2010, at 1:00 PM, Adriano Brandão wrote:

> Hi,
>
> 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)?
>
> PS: I followed the idea behind here (http://stackoverflow.com/questions/560517/how-to-set-the-float-value-to-two-decimal-number-in-objective-c) but it didn't work.

Perhaps something like this would be serviceable?

#include <math.h>
#include <stdio.h>

void display(double x)
{
    int p = x == floor(x) ? 0 : 2;
    printf("%.*f\n", p, x);
}

int main()
{
    display(25);
    display(25.256);
    display(25.5);
    display(5.5123);
}

25
25.26
25.50
5.51

-Howard

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

This email sent to email@hidden

References: 
 >Formatting float numbers (From: Adriano Brandão <email@hidden>)

  • Prev by Date: Formatting float numbers
  • Next by Date: Re: Formatting float numbers
  • Previous by thread: Formatting float numbers
  • Next by thread: Re: Formatting float numbers
  • Index(es):
    • Date
    • Thread