2

How can I use the math round function same as excel round function

float round( float arg );

round( number, num_digits )

  • If num_digits is greater than 0, then number is rounded to the specified number of decimal places.

  • If num_digits is 0, the number is rounded to the nearest integer.

  • If num_digits is less than 0, the number is rounded to the left of the decimal point.

Molham
  • 165
  • 1
  • 8
  • possible duplicate of [Round a float to a given precision](http://stackoverflow.com/questions/11208971/round-a-float-to-a-given-precision) – Cory Kramer May 21 '15 at 14:38
  • I don't think this is actually a duplicate of that, only because he wants to be able to round to the left of the decimal – iedoc May 21 '15 at 14:49

1 Answers1

3

simple arithmetic,

#include <stdio.h>
#include <cmath>

float my_round( float arg, int digits )
{
    float retValue = arg * pow(10.0f,(float)digits);
    retValue = round(retValue);
    return retValue * std::pow(10.0f,(float)-digits);
}


int main()
{
    float value = 12.3456789f;
    for(int i=-1;i<6;i++)
    {
            printf("%f\n", my_round(value, i));
    }
}

should do the trick, (compiled with g++)

output is :

10.000000
12.000000
12.300000
12.349999
12.346001
12.345699
12.345679
X3liF
  • 1,054
  • 6
  • 10