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
?
Asked
Active
Viewed 3,484 times
3

cpx
- 17,009
- 20
- 87
- 142
-
4It sounds like maybe you're asking how to round a number? You'll find a lot of previous questions if you search for that. – Cascabel Jun 18 '10 at 13:28
-
1Do you want to round numbers or truncate them? what should happen when n = 1.246? – Bill Carey Jun 18 '10 at 13:33
-
Yes, truncate the number and put it back to the variable 'n'. – cpx Jun 18 '10 at 13:33
4 Answers
7
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
- 204,818
- 23
- 294
- 489
6
#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
- 208,748
- 37
- 389
- 560
-
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 Jun 18 '10 at 13:43
-
@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 Jun 18 '10 at 13:47
3
Have a look at this question :
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;
-
Odd that this got downvoted, when it's the only answer mentioning display purposes, which could well be the OP's use case! +1. – Cascabel Jun 18 '10 at 13:50
-
@Jefromi : yep, don't know why it was downvoted. I wish the downvoter would put an explaination. Thx for upvoting ! – Jérôme Jun 18 '10 at 14:01