3

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 ?

cpx
  • 17,009
  • 20
  • 87
  • 142

4 Answers4

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;
Community
  • 1
  • 1
Jérôme
  • 26,567
  • 29
  • 98
  • 120
  • 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
2

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

Bill Carey
  • 1,395
  • 1
  • 11
  • 20