View previous topic :: View next topic |
Author |
Message |
pilar
Joined: 30 Jan 2008 Posts: 197
|
Float to Int16 |
Posted: Wed Sep 21, 2011 3:15 pm |
|
|
Hi, can anyone tell me how to convert float into integer.
example : if float value is 299.33 then i need only 299?
i just want to drop the decimal part. |
|
|
asmboy
Joined: 20 Nov 2007 Posts: 2128 Location: albany ny
|
|
Posted: Wed Sep 21, 2011 3:17 pm |
|
|
have you tried just casting ?
Code: |
unsigned int16 result;
float float_value=299.123;
result=(unsigned int16) float_value;
|
of course make sure the int that will hold the float is big enough ;-)) |
|
|
pilar
Joined: 30 Jan 2008 Posts: 197
|
|
Posted: Wed Sep 21, 2011 4:03 pm |
|
|
Quote: | have you tried just casting ?
| ???? |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19515
|
|
Posted: Thu Sep 22, 2011 2:01 am |
|
|
Get a C reference book.....
Casting, is the type conversion 'built into' C. You can cast explicitly (as shown by asmboy, by putting a type name into brackets in front of a value), or the language itself also casts automatically. If (for instance) you take:
Code: |
float val;
int16 ival, ival2;
ival=133;
val=ival;
//Here the language automatically casts the integer to a float
val=23.4;
ival=val;
//again here the language automatically casts the float to an integer ival=23
ival=23;
ival2=45;
val = ival/ival2;
ival=val;
//here the language calculates ival/ival2 as an _integer_ division
//since both values are integers, and then casts the result to val
//23/45 _integer_ is 0, so val becomes 0.00, and ival 0
val = (float)ival/ival2;
//here ival is converted to float, then divided by ival2. Since now one of the //values is 'float', the division is performed using float arithmetic - slower, //but gives val=0.51111.
|
It is a vital part of C, especially the need to force types 'up' before arithmetic.
Best Wishes |
|
|
|