• Register

When calculating big maths equations sometimes we get the result in the decimal form or we can say in float/double. And there are some fractions which never end even after the decimal, their size tends to infinity for example if we divide 10 by 3, the result will be 3.333333 and so on.

Since the digits after the decimal tend to the infinity so, the size of this variable will be infinity. Therefore we will need an infinite storage to store this variable but in practical we cannot do that. So as in maths, in programming we also round off the digits for our convenience.

In this article we will be discussing how to round off the digit by two. We can round off by using setprecision function but there are some other methods for rounding off. Methods for doing this are given below with examples

  • Using float precision

  • Using integer typecast

 

Note: The easiest method to round off is by using setprecision function. If you want to check how to use setprecision then check this article. https://kodlogs.com/blog/651/how-to-set-precision-in-c

Float precision

In this method we define the digit which will be defined by how much the number compiler has to round off. The syntax is as printf("%.2f", var);

#include <iostream> 
using namespace std; 
int main() 
{ 
    float var = 37.66666; 
  
    // Directly print the number with .2f precision 
    printf("%.2f", var);  
    return 0; 
} 

 

Integer typecast

This method is more dependent on little maths. The logic of this method is given below for the variable 28.6666

  1. 28.6666 * 100 = 2866.66

  2. 2866.66 + 0.5 = 2867.16

  3. Then typecast this variable into integer it will become 2867

  4. 2867/100 = 28.67 (this is what we want)

    #include <iostream> 
    using namespace std; 
    float round(float var) 
    { 
        // 37.66666 * 100 =3766.66 
        // 3766.66 + .5 =3767.16    for rounding off value 
        // then type cast to int so value is 3767 
        // then divided by 100 so the value converted into 37.67 
        float value = (int)(var * 100 + .5); 
        return (float)value / 100; 
    } 
      
    int main() 
    { 
        float var = 37.66666; 
        cout << round(var); 
        return 0; 
    } 

     

posted Jul 3 in c++ 100 points