-1

I have a floating point number, but I only want the number till 2 points of precision. How do I get this in C++?

float foo(float num) { // num=1234.567891
    // code
    return num2;           // returns 1234.560000
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
ofey
  • 423
  • 1
  • 7
  • 17

3 Answers3

1

A simple way would be:

float foo(float num) {
    return floor(num * 100) / 100;
}

You may also consider:

float foo(float num) {
    return (int)(num * 100) / 100.0f;
}

There might be differences with negative numbers. Only information I can get from your question is that for positive numbers you want floor (and not round for example).

Shahbaz
  • 46,337
  • 19
  • 116
  • 182
  • Do I typecast like (int)(expression) or like static_int(expression)? Or are they same? – ofey Feb 04 '13 at 13:07
  • `(int)(expression)` is C style. `static_cast(expression)` is C++ style. Whichever you choose should be the same (Note: I like C). If you have `dynamic_cast<>` and similar constructs, I advise the second form since it gives your code more regularity. – Shahbaz Feb 04 '13 at 13:11
0

You can attempt to round a floating point number to a certain number of decimal places, by multiplying and rounding/truncating.

So num = floor(num * 100.f) / 100.f; would try to truncate to two decimal places.

However note that this is not the same as fixing the precision of the float. By definition the decimal point in a floating point number floats. And you only have around 7 digits of precision.

So your original number cannot be as precise as "1234.567891" - this is too much precision for a float.

And perhaps more importantly, your output from such a function may also not be precise. "1234.56" cannot be exactly represented by a float, so the returned value will not be "1234.560000".

The larger the integer portion of the number, the less digits can be represented after the decimal point. Indeed, even a moderately large number cannot represent any fractional part at all.

JasonD
  • 16,464
  • 2
  • 29
  • 44
0

Floating-point types have their own internal precision. You can't change it. You can fiddle with the value in various ways, but ultimately the floating-point types manage their own precision, and you won't succeed in limiting what they do. Even if you manage to force a bunch of zeros into the low bits of some value, subsequent computations will still use the full precision, and you've only introduced some random noise into the computation.

What you can do is control the number of significant digits on input and output. And that's almost always the right way to manage precision.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165