Jan
Does anyone know how to round a double. I wrote a program basically a cashregister and i am getting 205.563 I need to get 205.56 or if it was 205.568 i need to get 205.57
thank you
Answer:
Or to make it cleaner and to be C friendly, you could use and abuse the Floor command.. which is in the
The way I will explain it will make it easier for you to change it so that you can round to the nearest tenth, hundredth, or thousandths easily by changing one variable. In this case we are using only hundredth which is represented as 100
===================================
double myNumA = 205.563;
double myNumB = 205.567;
double roundedNumA = floor( myNumA *100 0.5 ) / 100;
double roundedNumB = floor( myNumB *100 0.5 ) / 100;
cout << "NumA = " << roundedNumA << " NumB = " << roundedNumB;
===================================
The reason why I denoted 100 in the equation is to show you how to round to the nearest "hundredths", The reason why we multiply it by a 100, is to transform the double to the whole number then we adjust the decimal part by adding 0.5 to decide if its over the mid or below the mid. Then we transform it back to the original form disregarding the decimal places from "floor" by just dividing by 100.
So if you want to alter that code and round to the nearest tenth (0.x) or nearest hundredth (0.0x) or even thousandths (0.00x) you just change the 100 to its corresponding rounding, 10 (tenth), 100(hundredth), or 1000(thousandth)
Good Luck
Answer:
Add .005
Multiply by 100.0
Set an int equal to the result
Set a float equal to that int
divide the float by 100.0
double dCashUnrounded;
int nCash;
float fCashRounded;
nCash = (int)( (100.0) * (dCashUnrounded 0.005) );
fCashRounded = ((float)(nCash)) / (100.0);
Answer:
The easiest way would be like this…
char buff[20], double n;
cin>>n;
sprintf(buff, "%.2f", n);
n = atof(buff);
Where n is the number you wish to round off… And the rounded-off number will be stored to n.
Try this out.. (^^,) I think it'll work…
And don't forget to include stdlib.h or math.h, i think, for the atof() function… (^^,)
http://ronaldborla.blogsome.com/
Book Mark it-> del.icio.us | Reddit | Slashdot | Digg | Facebook | Technorati | Google | StumbleUpon | Window Live | Tailrank | Furl | Netscape | Yahoo | BlinkListTags: rounding