<< moderator edit: split thread (original) >>

I must have a bad version of Microsofts C++ compiler. When I try the rounding it doesn't work. For example.

float salesTotal =6.010002;
salesTotal = (((int)((salesTotal*100)+.5))/100.0);
// I realize I have plenty of parentheses.

results in a value of 6.010002 stored in the variable.
I have an academic version of Visual Studio .NET.
Any ideas?

Blame it on anything other than your own incompetence...

I like the way you think. :eek:

float t=6.0023;

cout<<int(t);

Does that work?

>I must have a bad version of Microsofts C++ compiler.
Yea, that's it exactly. :rolleyes: :rolleyes: :rolleyes:

>Does that work?
No, it doesn't. Casting a floating-point value to an integral value truncates rather than rounds. The precision will be lopped off, leaving the whole value unchanged. This works though:

#include <iostream>

using namespace std;

int main()
{
  double d = 6.0025;

  cout.precision ( 4 );
  cout<< d <<'\n';
}

http://cch.loria.fr/documentation/IEEE754/ACM/goldberg.pdf
Read this and understand how all floats are approximations, which means no matter what you do, you invariably end up with ab.cd0000001 or ab.cc999999 type numbers as being the nearest representable value to ab.cd

Using floats for storing money is a really bad idea.

Here is another way to round (maybe) the internal representation of a float.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.