rounding off to first decimal

Discussion in 'Embedded Systems and Microcontrollers' started by ak52, Apr 27, 2015.

  1. ak52

    Thread Starter Member

    Oct 15, 2014
    145
    4
    Hello everyone,

    I am looking to round my float value to a single digit after decimal,not just to display,but to use in mathematical calculations.
    Here is what i have so far:
    Code (Text):
    1.  
    2. float value = 5.65893    //example float
    3. int temp = 0;
    4.  
    5. temp = value*10;
    6. value = temp/10.00;
    7.  
    8. //value is 5.6
    9.  
    The above code works,but i need to use an extra variable temp for typecasting purpose.
    Is there a work around this??

    Thanks,
    AK
     
  2. MrChips

    Moderator

    Oct 2, 2009
    12,415
    3,354
    How about:

    value = round(value*10)/10;
     
  3. WBahn

    Moderator

    Mar 31, 2012
    17,715
    4,788
    But is 5.6 the answer you want if you are rounding 5.65893 to the nearest tenth?

    If you don't want to use a library routine, how about the following:

    value = ((int) (10*value+0.5))/10.0;
     
  4. ak52

    Thread Starter Member

    Oct 15, 2014
    145
    4
    I am using XC16 compiler, inst round used for integer values only?,Anyways i tried using round and roundf,both gave me error(i included math.h also).
    Round may not be the correct word here,sorry for that,i just need the first digit after the decimal point and ignore the rest for my calculations.
     
  5. WBahn

    Moderator

    Mar 31, 2012
    17,715
    4,788
    Then remove the 0.5 from the expression.

    The term you are looking for is "truncate" instead of round.

    How do you need to handle negative values? For instance, what result would you want for -5.67?
     
  6. ak52

    Thread Starter Member

    Oct 15, 2014
    145
    4
    I got it.Thanks for your help WBahn.
    Negative values is not a problem ,because i make sure that the values are always positive.

    AK
     
Loading...