Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding floating point numbers in C++ to one decimal place

I have a float number in c++ and the number can be in different forms, e.g. 355.5 or 9.9 (this is input from test code).

I have a function which is

float return_max(angle_set_t *angles)  
{  
    float val;  
    float max;  
    max= angles->key;  
    while( angles != NULL )  
    {  
        val= angles->key;  
        if(max<=val)  
        {  
            max=val;  
        }  
        angles = angles->right;  
    }       
    return max;
}  

max can be a float value. I want to round the value to one decimal place.

I need a general solution so it works for 355.555555 and 9.999999

float first_aset()
{
    //do somethig
    result=return_max();
    return result;
}

void main()
{
    if( first_aset(S, 357.0, 20.0 ) != 9.9 ||
        first_aset(T, 357.0, 20.0 ) != 9.9 )
    {
         printf("Error in wrap-around interval (3)\n");
         printf(" first in interval [357, 20) in S is %f, should be 9.9\n",
         first_aset(S, 357.0, 20.0 ) );
         printf(" first in interval [357, 20) in T is %f, should be 9.9\n",
         first_aset(T, 357.0, 20.0 ) );
    }
}

over here is the problem..the result is:

Error in wrap-around interval (3)

first in interval [357, 20) in S is 9.900000, should be 9.9

first in interval [357, 20) in T is 9.900000, should be 9.9

like image 507
abbas Avatar asked Nov 30 '22 09:11

abbas


1 Answers

Do

answer = static_cast<float>(static_cast<int>(number * 10.)) / 10.;

If instead you are just trying to display the value with that precision, try setprecision:

cout << setprecision(1) << number << endl;

In your code you're comparing a float to a double. This can only end badly (as will any floating point comparisons). It might (rarely) work if you compare to 9.9f

like image 127
JoshD Avatar answered Dec 16 '22 00:12

JoshD