Check float if negative - keil/STM32

Discussion in 'Embedded Systems and Microcontrollers' started by aamirali, Feb 25, 2014.

  1. aamirali

    Thread Starter Member

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

    Code ( (Unknown Language)):
    1. float my_num;
    2. /* do some calculation */
    3.  
    4. if( (int32_t)my_num < 0 )
    5. {
    6.     my_num = 0.0f;
    7. }
    8. else
    9. {
    10.    print_float_on_lcd(my_num);
    11. }
    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: Feb 25, 2014
  2. t06afre

    AAC Fanatic!

    May 11, 2009
    5,939
    1,222
  3. MrChips

    Moderator

    Oct 2, 2009
    12,449
    3,368
    why not use

    if (my_num < 0.0)
     
  4. aamirali

    Thread Starter Member

    Feb 2, 2012
    415
    1
    floats create further issues when compared....
     
  5. tshuck

    Well-Known Member

    Oct 18, 2012
    3,531
    675
    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: Feb 25, 2014
  6. Ian Rogers

    Member

    Dec 12, 2012
    158
    29
    The problem with the first bit of code
    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...
     
  7. ErnieM

    AAC Fanatic!

    Apr 24, 2011
    7,395
    1,607
    If you refuse to use MrChip's excellent idea there is another simple fix:


    Code ( (Unknown Language)):
    1. float my_num;
    2. /* do some calculation */
    3.  
    4. if( (int32_t)[B]my_num <= 0[/B] )
    5. {
    6.     my_num = 0.0f;
    7. }
    8. else
    9. {
    10.    print_float_on_lcd(my_num);
    11. }
     
Loading...