Computer Science, asked by praneethasalihundam, 11 months ago

how to get float value upto 2 decimals in C++

Answers

Answered by 456789aman
0

Answer:

For example, 5.567 should become 5.57 and 5.534 should become 5.53

First Method:- Using Float precision

filter_none

edit

play_arrow

brightness_4

#include <iostream>

using namespace std;

int main()

{

   float var = 37.66666;

 

   // Directly print the number with .2f precision

   printf("%.2f", var);  

   return 0;

}

Output:

37.67

Second Method : Using integer typecast If we are in Function then how return two decimal point value

filter_none

edit

play_arrow

brightness_4

#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;

}

Output:

37.67

Explanation:

HOPE  IT WAS HELPFUL.

PLEASE MARK AS BRAINLIST AND FOLLOW ME AND SHRADDHA537

Similar questions