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?
2 decimal places in C
Started by
BTPH
, Sep 01 2005 11:14 PM
#1
Posted 01 September 2005 - 11:14 PM
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?
#2
Posted 02 September 2005 - 07:31 AM
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, ...
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 ); }
Similar Topics
0 user(s) are reading this topic
0 members, 0 guests, 0 anonymous users