Amsterdam
Offline
Full Member
Karma: 0
Posts: 136
he's looking at you, kiddy...
|
 |
« on: December 06, 2009, 03:55:33 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.
|
|
|
|
|
Logged
|
-- "We're all in this together..."
|
|
|
|
SE USA
Offline
Faraday Member
Karma: 33
Posts: 3626
@ssh0le
|
 |
« Reply #1 on: December 06, 2009, 04:00:24 pm » |
there is an int() typecast function http://arduino.cc/en/Reference/IntCastbut i have no idea what happens if you feed it a float (should just truncate it?)
|
|
|
|
|
Logged
|
http://arduino.cc/forum/index.php?action=unread;boards=2,3,4,5,67,6,7,8,9,10,11,66,12,13,15,14,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,86,87,89,1;ALL
|
|
|
|
Amsterdam
Offline
Full Member
Karma: 0
Posts: 136
he's looking at you, kiddy...
|
 |
« Reply #2 on: December 06, 2009, 04:45:04 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.
|
|
|
|
|
Logged
|
-- "We're all in this together..."
|
|
|
|
Huntsville, Alabama, USA
Offline
Sr. Member
Karma: 0
Posts: 327
Arduino rocks
|
 |
« Reply #3 on: December 06, 2009, 06:17:31 pm » |
If you do this: 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: float f; int i;
f = 3.14159; i = f + 0.5; // i is now 3 f = 3.6; i = f + 0.5; // i is now 4 Regards, -Mike
|
|
|
|
|
Logged
|
|
|
|
|
Amsterdam
Offline
Full Member
Karma: 0
Posts: 136
he's looking at you, kiddy...
|
 |
« Reply #4 on: December 06, 2009, 07:09:43 pm » |
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
|
|
|
|
|
Logged
|
-- "We're all in this together..."
|
|
|
|
SE USA
Offline
Faraday Member
Karma: 33
Posts: 3626
@ssh0le
|
 |
« Reply #5 on: December 06, 2009, 07:12:09 pm » |
both post are good to know info
|
|
|
|
|
Logged
|
http://arduino.cc/forum/index.php?action=unread;boards=2,3,4,5,67,6,7,8,9,10,11,66,12,13,15,14,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,86,87,89,1;ALL
|
|
|
|
Brooklyn, NY
Offline
Newbie
Karma: 0
Posts: 5
|
 |
« Reply #6 on: June 12, 2010, 09:39:52 pm » |
got it, thanks.
|
|
|
|
|
Logged
|
|
|
|
|
|