tags:

views:

206

answers:

5

Is there a way to round floating points to 2 points? ex: 3576.7675745342556 becomes 3576.76.

Thanks

+3  A: 
round(x * 100) / 100.0

If you must keep things floats:

roundf(x * 100) / 100.0
strager
+2  A: 

Multiply by 100, round to integer (anyway you want), divide by 100. Note that since 1/100 cannot be represented precisely in floating point, consider keeping fixed-precision integers.

Tassos Bassoukos
Decimal fixed-point integers are quite possibly the real right answer here.
caf
A: 
yourFloatNumber= Float.Round(yourFloatNumber,2); // In C#
Controler
That does work in Java. If you look carefully, the poster has tagged it with c/c++.
tholomew
+10  A: 

Don't do it. You have no good reason to lose the precision in your calculations. (Also if this is performance intensive loop, keep in mind the cast from float to int as mentioned above flushes the pipeline cache).

The only reason you would want to do that is when you are printing it out. In which case instead use whatever print formatting function available to you.

In c++

cout << setprecision(2) << f; 

Edit: In the case you need to round for converting to a string and passing to a method, the numerical method is fine. However, std::ostringstream can help you here as well.

tholomew
Never refer to another answer with "as mentioned above". The order in which answers are displayed varies over time and according to user-configurable preferences (sort by time or number of votes). To address your particular point, `floor` or `ceil` can be used instead of an integer cast.
Ben Voigt
Why not use `printf`?
Svante
@Svante , because we are using C++?
Craig
I apologise, i didn't see he marked C and C++
Craig
While cout might be preferred in C++, you can use printf in C or C++. E.g. std::printf("Printf C++\n");
bn
What I meant is `printf("%.2f", f);`.
Svante
@svante printf("%.2f", f) is also fine.
tholomew
A: 

Don't use floats. Use integers storing the number of cents and print a decimal point before the last 2 places if you want to print dollars. Floats are almost always wrong for money unless you're doing simplistic calculations (like naive economic mathematical models) where only the magnitude of the numbers really matters and you never subtract nearby numbers.

R..