Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

decimal question

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
if i have a floating point number eg.

float number = 2001.08;

how can I round this number to one decimal place precison(eg. 2001.08 becomes 2001.5, or 2001.14 becomes 2001.1) and copy that decimal number(which is "one" in this case) to a variable called decimal_number using the sprintf() function?

int decimal_number = 1;
float numberB = 2001.1;

Apart from using sprintf(), are there any other ways to perform this conversion? I'm not sure how to write this in C.

Many thanks!

 
Example:
float x;
int ix;
x=2001.18; // should be rounded to 1 place
ix = x*10+0.5; // x =20012.3 ix=20012;
x = ix/10; // x= 2001.2

hnd
hasso55@yahoo.com

 
And for the later part of ur question Checkout an easy way---

deci_digit = (x*10) % 10;

hope that helps,
SwapSawe. |-0
 
To. hnd (Programmer)

In source...

Example:
float x;
int ix;
x=2001.18; // should be rounded to 1 place
ix = x*10+0.5; // x =20012.3 ix=20012;
x = ix/10; // x= 2001.2

finally, have x 2001.2 ???

i think that x have 2001.000000. ^^;

be happy~
 
1. jongheeyun, you were hasty for this problem.
hnd's code is sufficient pseudo code to show
how to round off a value. He just missed a comma.

x = ix/10.;
or
x = (float)/10.f; /* more strict type conversion */

Because 'ix' is integer. But you can know
how to do it by his answer.

2. I suggest another way which uses floor.

floor( x*10.+.5 )/10.

will do the same without integer conversion.

It is preferable to use 'double' instead of 'float'
to maintain accuracy. Sometimes printf can show
2001.199951 instead of 2001.2 if single precision
floating point is used.

Hee S. Chung
heesc@netian.com
 
Á¤Èñ¼®´Ô °¨»ç ÇÕ´Ï´Ù.
´öºÐ¿¡ ¸ô¶ú´ø »ç½ÇÀ» ¾Ë¾Ò³×¿ä ^^

ÇູÇϼ¼¿ä.

[Yun jonghee # À± Á¾Èñ]
jongheeyun@linux.co.kr
 
Thank you jongheeyun. HaHa... you are Korean too,
and only Korean can read your reply. :)

And I need to correct this :
x = (float)/10.f; /* I missed ix */

It should be
x = (float)ix/10.f;

Happy coding everybody !
Hee S. Chung
heesc@netian.com
 
Take care:
These rounding algorithms are valid for positive numbers only.
hnd
hasso55@yahoo.com

 
Here is complete routine which considers negative values :

based on hnd's code :
x = (double)(int)( x*10. + ( x>0? 0.5 : -0.5 ) ) / 10.;

based on my code :
x = ( x>0? floor( x*10.+.5 ) : ceil( x*10.-.5 ) ) / 10.;

Thanks
Hee S. Chung
heesc@netian.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top