Tuesday, June 12, 2012

Rounding floating point numbers

If you are an experienced programmer definitely you faced to issues with floating point rounding. Actually this is due to the values keeping format of the floating point data types. In simply float and double like data types storing the numbers in memory as powers. So the value return back may not be the exact value you stored at  the variable.

As example if you store 444.25 555.25 and  in float variable it the return back value may be

444.24999999999999 or 555.25000000000001

This happens because of the value storing format of the memory you can look in more information about value keeping structure here.

The Problem comes when you try to round the value you store in the float variable
As our example
If value store as 444.24999999999999 then round value will be 444.2 for one decimal point
If value store as 555.2500000000001 then round value will be the 555.3 for one decimal point.

So same kind of values get different kind of result when you round. If you like you can read more about this here

Ok, what we can do to avoid this rounding issue when you do programming with C++. fallowing is my proposed method to avoid the issue. Don't use the standers rounding functions and  use a own rounding function

#include <iostream>
#include <math.h>

using namespace std;

double flaotRound( double dblNumber,int intNoOfDecPoint  ){
 double dblTemp = pow(10.0,intNoOfDecPoint);
 return int(dblNumber*dblTemp + (dblNumber<0? -0.5 : 0.5))/dblTemp;
}

void main(){
 //char array for input (to pause programe)
 char chrTempInput[100];
 double dblValue;

 for(int i = 0; i <1000 ; i++){
  dblValue = (double)rand()/rand();
  cout << dblValue << " - " << flaotRound(dblValue,2) << endl;
  }

 cin >> chrTempInput;
}