Go Down

### Topic: Typecasting or rounding off... (Read 10197 times)previous topic - next topic

#### macsimski

##### Dec 06, 2009, 09:55 pm
hello all,

if i want to convert and round a float to a int, how would i do that?

int(floatVar)?

background:

i am calculating the sin(x) function to ramp up a stepper to full speed, but i use a for loop to do the actual clockpulses to the TA8439H stepper chip. so the result of the calculation should be a int.

--
"We're all in this together..."

#### Osgeld

#1
##### Dec 06, 2009, 10:00 pm
there is an int() typecast function

http://arduino.cc/en/Reference/IntCast

but i have no idea what happens if you feed it a float (should just truncate it?)

#### macsimski

#2
##### Dec 06, 2009, 10:45 pm
yeah, i know. the page is very brief to say the least. pages on the web deal mostly with upcasting (int>double) but not downcasting. i now use the trial-and-error methode to find out...

but there is another problem in my code that prevents me from finding out.
--
"We're all in this together..."

#### mfm9

#3
##### Dec 07, 2009, 12:17 am
If you do this:
Code: [Select]
`float f;int i;f = 3.14159;i = f;`Then the value of 'i' will be 3.  In other words, when a float is converted to an int, the decimal portion of the float is thrown away.  This is also known as 'truncation'.

If you want to round the floating point value up or down to the nearest integer, just add 1/2 to it before converting:
Code: [Select]
`float f;int i;f = 3.14159;i = f + 0.5;   // i is now 3f = 3.6;i = f + 0.5;  // i is now 4`

Regards,

-Mike

#### macsimski

#4
##### Dec 07, 2009, 01:09 am
well, i circumfenced the other problem and can confirm that casting down from float to int works for me. be shure you do it for the whole calculation, so all the other variables cast themselves as a float to before you round it off to a int
--
"We're all in this together..."

#### Osgeld

#5
##### Dec 07, 2009, 01:12 am
both post are good to know info