abbas
abbas

Reputation: 143

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

Upvotes: 5

Views: 46070

Answers (5)

Maifee Ul Asad
Maifee Ul Asad

Reputation: 4607

Use this function, looks complicated, but it is what is asked :

float float_one_point_round(float value)
{
        return ((float)((int)(value * 10))) / 10;
}

Upvotes: 2

fredoverflow
fredoverflow

Reputation: 263038

As a side note, you seem to be building your own (intrusive) linked list. C++ already provides various containers for you such as vector and list. Also, you don't have to write a function that determines the maximum value in a sequence, just use an appropriate algorithm from the standard library.

#include <vector>
#include <algorithm>

std::vector<float> angles = {0.0, 355.5, 9.9};
float maximum = *std::maximum_element(angles.begin(), angles.end());

Upvotes: 1

JoshD
JoshD

Reputation: 12824

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

Upvotes: 9

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

rounded = truncf(original * 10) / 10;

However, I agree with Ben that you should definitely not be checking for exact inequality. Use an epsilon if a comparison is needed.

Upvotes: 4

Related Questions