How would you change the precision of a number for example: float n = 1.2345 and store it back to the variable 'n' with changing it to 1.23 ?
views:
95answers:
4
+4
A:
#include <cmath>
n = roundf(n * 100.0f) / 100.0f;
or if you need to truncate rather than round:
n = truncf(n * 100.0f) / 100.0f;
Paul R
2010-06-18 13:31:28
Just a note: this rounds the floating point number instead of truncating it, which may or may not be what Dave18 is looking for.
Bill Carey
2010-06-18 13:43:02
@Bill: indeed - I was updating it to include the possibility of truncation at the exactly the same time that you were adding your comment. ;-)
Paul R
2010-06-18 13:47:12
+1
A:
float truncated = static_cast<int>(n * 100) / 100.0f ought to work.
Bill Carey
2010-06-18 13:31:30
+3
A:
float n = 1.2345;
int scaled = n * 100
n = static_cast<float>(scaled)/100.0;
or in one line:
n = static_cast<float>( static_cast<int>(n*100) ) / 100;
David Rodríguez - dribeas
2010-06-18 13:31:35
+1
A:
Have a look at this question :
http://stackoverflow.com/questions/1343890/rounding-number-to-2-decimal-places-in-c
However, in C++, if you need to round a number for display purpose, I wouldn't use printf, but use the stream operators :
using namespace std;
cout << setiosflags(ios::fixed) << setprecision(2);
cout << n;
Jérôme
2010-06-18 13:34:37