Reputation: 17577
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
?
Upvotes: 3
Views: 3508
Reputation: 213170
#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;
Upvotes: 6
Reputation: 1415
float truncated = static_cast<int>(n * 100) / 100.0f
ought to work.
Upvotes: 2
Reputation: 27047
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;
Upvotes: 3
Reputation: 208446
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;
Upvotes: 7