Check float if negative - keil/STM32

Thread Starter

aamirali

Joined Feb 2, 2012
412
I have to check if float number is negative or not. If negative assign it zero otherwise print it So what I did was:

Rich (BB code):
float my_num;
/* do some calculation */

if( (int32_t)my_num < 0 )
{
    my_num = 0.0f;
}
else
{
   print_float_on_lcd(my_num);
}
The above code fails for float values less in range less than -0.9.
for example if number is -0.001, -0.0000006 then it fails . How to implement in C.
 
Last edited by a moderator:

tshuck

Joined Oct 18, 2012
3,534
You could cast the referenced location to a byte pointer and dereference it once you add the offset to the most-significant byte, and AND with 0x80 to determine if the sign bit is set...

This is probably what MrChips' suggestion does..
 
Last edited:

Ian Rogers

Joined Dec 12, 2012
1,136
The problem with the first bit of code
if( (int32_t)my_num < 0 )
Is the cast is performed first... So the comparison is done against the 32bit long and not the float... MrChips's logic is the correct one...
 

ErnieM

Joined Apr 24, 2011
8,377
If you refuse to use MrChip's excellent idea there is another simple fix:


Rich (BB code):
float my_num;
/* do some calculation */

if( (int32_t)my_num <= 0 )
{
    my_num = 0.0f;
}
else
{
   print_float_on_lcd(my_num);
}
 
Top