 Open in App
Not now

# Rounding Floating Point Number To two Decimal Places in C and C++

• Difficulty Level : Medium
• Last Updated : 07 Aug, 2021

How to round off a floating point value to two places. For example, 5.567 should become 5.57 and 5.534 should become 5.53

First Method:- Using Float precision

## C++

 `#include` `using` `namespace` `std;`   `int` `main()` `{` `    ``float` `var = 37.66666;`   `    ``// Directly print the number with .2f precision` `    ``cout << fixed << setprecision(2) << var; ` `    ``return` `0;` `}`   `// This code is contributed by shivanisinghss2110`

## C

 `#include ` `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

## C++

 `#include ` `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```

Third Method: using sprintf() and sscanf()

## C++

 `#include ` `using` `namespace` `std;` `float` `round(``float` `var)` `{` `    ``// we use array of chars to store number` `    ``// as a string.` `    ``char` `str; `   `    ``// Print in string the value of var ` `    ``// with two decimal point` `    ``sprintf``(str, ``"%.2f"``, var);`   `    ``// scan string value in var ` `    ``sscanf``(str, ``"%f"``, &var); `   `    ``return` `var; ` `}`   `int` `main()` `{` `    ``float` `var = 37.66666;` `    ``cout << round(var);` `    ``return` `0;` `}`

```Output:
37.67```

This article is contributed by Devanshu Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.