VOOZH about

URL: https://www.geeksforgeeks.org/cpp/precision-of-floating-point-numbers-in-c-floor-ceil-trunc-round-and-setprecision/

⇱ Precision of Floating Point Numbers in C++ (floor(), ceil(), trunc(), round() and setprecision()) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Precision of Floating Point Numbers in C++ (floor(), ceil(), trunc(), round() and setprecision())

Last Updated : 2 Nov, 2022

The decimal equivalent of 1/3 is 0.33333333333333…. An infinite length number would require infinite memory to store, and we typically have 4 or 8 bytes. Therefore, Floating point numbers store only a certain number of significant digits, and the rest are lost. The precision of a floating-point number defines how many significant digits it can represent without information loss. When outputting floating-point numbers, cout has a default precision of 6 and it truncates anything after that. Below are a few libraries and methods which are used to provide precision to floating-point numbers in C++:

1. floor() Method

Floor rounds off the given value to the closest integer which is less than the given value. It is defined in the <cmath> header file.


Output
1
1
1
-2
-2
-2

Time Complexity: O(1)

Auxiliary Space: O(1)

2. ceil() Method

Ceil rounds off the given value to the closest integer which is more than the given value. It is defined in the <cmath> header file.


Output
2
2
2
-1
-1
-1

Time Complexity: O(1)

Auxiliary Space: O(1)

3. trunc() Method

Trunc rounds remove digits after the decimal point. It is defined in the <cmath> header file.


Output
1
1
1
-1
-1
-1

Time Complexity: O(1)

Auxiliary Space: O(1)

4. round()

Rounds gave numbers to the closest integer. It is defined in the header files: <cmath> and <ctgmath>.


Output
1
2
2
-1
-2
-2

Time Complexity: O(1)

Auxiliary Space: O(1)

5. setprecision()

Setprecision when used along with 'fixed' provides precision to floating-point numbers correct to decimal numbers mentioned in the brackets of the setprecision. It is defined in header file <iomanip>.


Output
3 -3
3.1 -3.1
3.14 -3.14
3.142 -3.142
3.1416 -3.1416
3.14159 -3.14159
3.141590 -3.141590

Time Complexity: O(1)

Auxiliary Space: O(1)

Note: When the value mentioned in the setprecision() exceeds the number of floating point digits in the original number then 0 is appended to floating point digit to match the precision mentioned by the user.

There exist other methods too to provide precision to floating-point numbers. The above mentioned are a few of the most commonly used methods to provide precision to floating-point numbers during competitive coding.

Comment
Article Tags: