Search code examples
c++floating-point-precision

How to round off a variable to n decimal places in c++


I have some float variables that would yield values like 1.23456789. I want to round it off to, say 4 decimal places.

the setprecision function only roundoffs output, but I want to change the value of variable itself.

So I'm looking for something like

x=roundoff(x,n)

where roundoff will round off x to n decimal places.


Solution

  • Why not this?

      float val = 1.23456789
    
      float rounded_down = floorf(val * 1000) / 1000;   /* 1.2345 */
    

    EDIT:

    as pointed out in the comments keep in mind that this is an approximation, but it might be acceptable in many situations. Also yo might want to round to the nearest value or to round up as follows:

      float val = 1.23456789
    
      float near = roundf(val * 1000) / 1000;   /* nearest */
      float up = ceilf(val*1000) / 1000; /* up*/