Jump to content

Welcome to Geeks to Go - Register now for FREE

Geeks To Go is a helpful hub, where thousands of volunteer geeks quickly serve friendly answers and support. Check out the forums and get free advice from the experts. Register now to gain access to all of our features, it's FREE and only takes one minute. Once registered and logged in, you will be able to create topics, post replies to existing threads, give reputation to your fellow members, get your own private messenger, post status updates, manage your profile and so much more.

Create Account How it Works
Photo

2 decimal places in C


  • Please log in to reply

#1
BTPH

BTPH

    Member

  • Member
  • PipPipPip
  • 167 posts
okay im doing some calculations and i need my numbers rounded to 2 decimal places, im using C.

if defined all my values as doubles and im using %lf for all the scanf'sa and printf's but it goes to too many decimal places, i remember something about putting a number (say 6.2) in between the % (%6.2lf) but i dont want to restric the high numbers, just the decimals, how can i do this?
  • 0

Advertisements


#2
bdlt

bdlt

    Member

  • Member
  • PipPipPip
  • 875 posts
here's some rounding code to play with.

using %6.2 does not restrict a large number. the 6 means display at least 6 digits(including the decimal point and 2 digits after the decimal point). experiment - try %12.5, %3.0, ...


void decimals_2(  ) {
  double d = 1234.5678;
  double rounded = 0.0;

  printf("%lf \n", d );                /* show entire double */
  printf("rounded?    %6.2lf \n", d ); /* appears to be rounded */
  printf("not rounded %6.3lf \n", d ); /* but it isn't */

  /* 
	d * 100.0 shift decimal 2 places right
    + 0.5     for rounding
	(int)     cast to int 
  */
  int n = (int)( d * 100.0 + 0.5 );

  /* shift decimal 2 places left */
  rounded = n / 100.0;
  
  /* use %6.2 to show only 2 decimal places */
  printf("rounded?    %6.2lf \n", rounded );

  /* use %6.3 to verify rounding */
  printf("yes         %6.3lf \n", rounded );
}

  • 0






Similar Topics

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

As Featured On:

Microsoft Yahoo BBC MSN PC Magazine Washington Post HP