tags:

views:

95

answers:

4

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 ?

+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
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
@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
+1  A: 

float truncated = static_cast<int>(n * 100) / 100.0f ought to work.

Bill Carey
+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
+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
Odd that this got downvoted, when it's the only answer mentioning display purposes, which could well be the OP's use case! +1.
Jefromi
@Jefromi : yep, don't know why it was downvoted. I wish the downvoter would put an explaination.Thx for upvoting !
Jérôme