Need help with your computer or device? Want to learn new tech skills? You're in the right place!
Geeks to Go is a friendly community of tech experts who can solve any problem you have. Just create a free account and post your question. Our volunteers will reply quickly and guide you through the steps. Don't let tech troubles stop you. Join Geeks to Go now and get the support you need!

How it Works Create Account

# 2 decimal places in C

### #1 BTPH Posted 01 September 2005 - 11:14 PM

BTPH

Member

• Member
• 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

### #2 bdlt Posted 02 September 2005 - 07:31 AM

bdlt

Member

• Member
• 876 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