15

Is there a way to round floating points to 2 points? E.g.: 3576.7675745342556 becomes 3576.76.

jmasterx
  • 52,639
  • 96
  • 311
  • 557
  • 4
    Do you mean for display or calculation? –  Aug 01 '10 at 21:30
  • 2
    3576.7675745342556 becomes 3576.77, doesn't it? – Vladimir Aug 01 '10 at 21:43
  • 2
    @Vladimir: Not nesacerily. rounding is a vague term that encapsulates several different operations that have more exact meaning. Round Up/Down/Towards Zero/Towards Infinity/Towards nearest int etc. – Martin York Aug 01 '10 at 21:51

9 Answers9

19
round(x * 100) / 100.0

If you must keep things floats:

roundf(x * 100) / 100.0

Flexible version using standard library functions:

double GetFloatPrecision(double value, double precision)
{
    return (floor((value * pow(10, precision) + 0.5)) / pow(10, precision)); 
}
strager
  • 88,763
  • 26
  • 134
  • 176
  • 3
    Note that because binary floating point can't represent most decimal values exactly, this answer won't work when you start examining the lower digits closely. But then again neither can any other answer. – Mark Ransom May 18 '13 at 01:28
  • Why do you use `floor` instead of `round` in the more flexible version? – pooya13 Jan 06 '21 at 02:01
  • `value * pow(10, precision) + 0.5` approach fails 1) many negative values, 2) the addition incurs imprecision in half-way cases, 3) multiplication overflows. – chux - Reinstate Monica Jan 06 '21 at 03:43
14

If you are printing it out, instead use whatever print formatting function available to you.

In c++

cout << setprecision(2) << f; 

For rounding to render to GUI, use std::ostringstream

carlsborg
  • 2,628
  • 19
  • 21
  • 5
    Never refer to another answer with "as mentioned above". The order in which answers are displayed varies over time and according to user-configurable preferences (sort by time or number of votes). To address your particular point, `floor` or `ceil` can be used instead of an integer cast. – Ben Voigt Aug 01 '10 at 23:49
  • 1
    @Svante , because we are using C++? – Craig Aug 02 '10 at 01:48
  • 1
    While cout might be preferred in C++, you can use printf in C or C++. E.g. std::printf("Printf C++\n"); – bn. Aug 02 '10 at 02:48
  • 1
    What I meant is `printf("%.2f", f);`. – Svante Aug 02 '10 at 08:33
  • what # include is this? – mLstudent33 Apr 26 '20 at 23:00
3

For those of you googling to format a float to money like I was:

#include <iomanip>
#include <sstream>
#include <string>

std::string money_format (float val)
{
    std::ostringstream oss;

    oss << std::fixed << std::setfill ('0') << std::setprecision (2) << val;

    return oss.str();
}
// 12.3456 --> "12.35"
// 1.2 --> "1.20"

You must return it as a string. Putting it back into a float will lose the precision.

xinthose
  • 3,213
  • 3
  • 40
  • 59
3

Multiply by 100, round to integer (anyway you want), divide by 100. Note that since 1/100 cannot be represented precisely in floating point, consider keeping fixed-precision integers.

Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40
2

Don't use floats. Use integers storing the number of cents and print a decimal point before the last 2 places if you want to print dollars. Floats are almost always wrong for money unless you're doing simplistic calculations (like naive economic mathematical models) where only the magnitude of the numbers really matters and you never subtract nearby numbers.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
1

try use

std::cout<<std::setprecision(2)<<std::cout<<x;

should works and only 2 digit after the floating point appear.

1

Try this, it works perfectly

float=3576.7675745342556;
printf("%.2f",float);

change some objects in it to see and learn the code.

1

I didn't find a clean answer that satisfied me since most of the clean answers assume you need to print the result which might not be the case if you are just storing some data to the acceptable resolution:

#include <sstream>

template<typename T>
T toPrecision(T input, unsigned precision)
{
    static std::stringstream ss;

    T output;
    ss << std::fixed;
    ss.precision(precision);
    ss << input;
    ss >> output;
    ss.clear();

    return output;
}

template<unsigned P, typename T>
T toPrecision(T input) { return toPrecision(input, P); }

// compile-time version
double newValue = toPrecision<2>(5.9832346739); // newValue: 5.98
// run-time version
double newValue = toPrecision(3.1415, 2); // newValue: 3.14

You can also add static checks for T and precision (in the case of the compile-time signature).

pooya13
  • 2,060
  • 2
  • 23
  • 29
0

To limit the precision:
If x is a float, no rounding:
(shift up by 2 decimal digits, strip the fraction, shift down by 2 decimal digits)

((int)(x*100.0)) / 100.0F

Float w/ rounding:

((int)(x*100.0 + 0.5F)) / 100.0F

Double w/o rounding:

((long int)(x*100.0)) / 100.0

Double w/ rounding:

((long int)(x*100.0 + 0.5)) / 100.0

Note: Because x is either a float or a double, the fractional part will always be there. It is the difference between how a # is represented (IEEE 754) and the #'s precision.
C99 supports round()

Doug
  • 2,783
  • 6
  • 33
  • 37
  • `(int)(x*100.0)` fails when the product is out of `int` range. Even using `intmax_t` is insufficient. `x*100.0 + 0.5F` fails like [this](https://stackoverflow.com/questions/3383817/limit-floating-point-precision#comment115965369_3383822). – chux - Reinstate Monica Jan 06 '21 at 03:46