## Algorithms

Moderators: None (Apply to moderate this forum)
Number of threads: 384
Number of posts: 762

This Forum Only

Math (rounding to the nearest hundreth) Posted by pnezzy on 11 Dec 2002 at 1:13 PM
Dunno, maybe this is a stupid question, but I've had trouble finding anything about rounding numbers in basic C++. I'm sorta new at this so if yall could give me a bit of help on this. Anyways, later!

Re: Math (rounding to the nearest hundreth) Posted by Josh Code on 15 Dec 2002 at 12:29 AM
: Dunno, maybe this is a stupid question, but I've had trouble finding anything about rounding numbers in basic C++. I'm sorta new at this so if yall could give me a bit of help on this. Anyways, later!
:
:

Here is some code for a console app that should help:
```#include <stdio.h>
#include <iostream.h>

int main(int argc, char *argv[])
{
float f;
float rounded;
f = 2.71828182845904523536028747135266;
rounded = (int)(f*100); // rounded = 271
cout << rounded;
cout << '\n'; // break the line
rounded /= 100; // rounded = 2.71
cout << rounded;
while (0==0) // keep the console open so you can see the outputs
{}
return 0;
}```

The "(int)" means the result of the multiplication is truncated. It is a little different from rounding. With normal rounding, it would round up to 2.72 but instead the rest of the number is ignored.

Re: Math (rounding to the nearest hundreth) Posted by rolle on 5 Mar 2003 at 5:50 AM
: : Dunno, maybe this is a stupid question, but I've had trouble finding anything about rounding numbers in basic C++. I'm sorta new at this so if yall could give me a bit of help on this. Anyways, later!
: :
: :
:
:
: Here is some code for a console app that should help:
:
```: #include <stdio.h>
: #include <iostream.h>
:
: int main(int argc, char *argv[])
: {
: float f;
: float rounded;
:       f = 2.71828182845904523536028747135266;
:       rounded = (int)((f+0.005)[/size]*100); // rounded = 271
:       cout << rounded;
:       cout << '\n'; // break the line
:       rounded /= 100; // rounded = 2.71
:       cout << rounded;
:       while (0==0) // keep the console open so you can see the outputs
:       {}
:       return 0;
: }```

:
: The "(int)" means the result of the multiplication is truncated. It is a little different from rounding. With normal rounding, it would round up to 2.72 but instead the rest of the number is ignored.
:
:
:
If you would rather have the value rounded and not truncated, see red
Re: Math (rounding to the nearest hundreth) Posted by pnezzy on 5 Mar 2003 at 7:44 AM
Thanks a lot! These are a lot simpler than the way I figured out. Awesome.

## Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic