Fabian Orue
Fabian Orue

Reputation: 193

truncate a very large float to 2 digits c++

would need help understanding how I can solve this problem.

I have a float number (these are dynamic numbers, no static) whose value is, for example:

-27.8738e007

I need to truncate to 2 digits (-27.87), but I'm not succeeding.

I've tried different forms, but nothing works for that "e" in the number ...

For example:

float number = -27.8738e007;

int decimals = 2;
number = (roundf (number * pow (10, decimals)) / pow (10, decimals));

this returns -2.787383 + 008 and I need get -27.87

Thanks in advance

Greetings

Upvotes: 0

Views: 340

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118425

Looks like you're not familiar with how scientific notation works.

-27.8738e007 is -278738000, or -2.787380e+08

Truncation or rounding to "n" digits generally refers to rounding a number to the given number of digits after the decimal point. This is what the code that you posted is trying to accomplish.

Of course, -278738000 rounded to two digits after the decimal point is still the same number, which is the answer you're getting.

-27.87380e+07 is 2.787380e+08

It's the same number.

See http://en.wikipedia.org/wiki/Scientific_notation

Upvotes: 3

Related Questions