We help IT Professionals succeed at work.

How do I convert float to int that's rounded off to nearest hundred?

shaolinfunk
shaolinfunk asked
on
Let's say I have a float variable fNumber.

fNumber is usually some number with decimals to the thousandth place.  I want to convert fNumber to an unsigned int that rounds to the nearest 100.  thats' right, 100.  with the caveat that any number between 0-99 is rounded up to 100.

so if fNumber is 1234.238, the new unsigned int should be 1200.
if fNumber is 32.589, the new unsigned int should be 100 instead of 0.  

how do i do this?  
Comment
Watch Question

See if this works for you.

unsigned int ival = (fval<100)?100:(unsigned int)((fval+50.0)/100.0)*100;

Open in new window

Assumption is that you ensure that float fval is >= 0.
HI. If you know type casting in C++ and casting in C, then use this link for your logic.

http://www.enchantedlearning.com/math/rounding/
Try this:

    float f;
    long n;

    f = 1234.567; // initialise with some test value
    n = (long)f; // convert to an integral value
    if(n<99)
       n = 100;

    n /= 100;
    n = n * 100;

Author

Commented:
works for me, thanks!
   //Try This :

    float f;
    int n;

   
    f = 1254.567;

    n = (int)f;

    if(n<99)
        n = 100;
    else
    {
        if((n%100)>=50)
            n+=100;
    }
    n /= 100;
    n = n * 100;
If you stick the below function in a header, it will convert the float input more efficiently since it is only using integer arithmetic for the rounding.
inline unsigned int roundHundreds(float fval) {
   unsigned int ival = (unsigned int)fval;
   return (ival>100)?((ival+50)/100)*100:100;
}

Open in new window