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 <stdio.h>
int main()
{
float var = 37.66666;
printf ( "%.2f" , var);
return 0;
}
|
C++
#include<bits/stdc++.h>
using namespace std;
int main()
{
float var = 37.66666;
cout << fixed << setprecision(2) << var;
return 0;
}
|
Time Complexity: O(1), as the execution time does not depend on the size of the input.
Space Complexity: O(1), as it only uses a fixed amount of memory to store a single float variable and does not allocate any dynamic memory.
Second Method: Using integer typecast If we are in Function then how return two decimal point value
C++
#include <iostream>
using namespace std;
float round( float var)
{
float value = ( int )(var * 100 + .5);
return ( float )value / 100;
}
int main()
{
float var = 37.66666;
cout << round(var);
return 0;
}
|
Output:
37.67
Time complexity:
The round function only performs a few basic arithmetic operations, so its time complexity is constant or O(1).
Space complexity:
The round function creates a single float variable named value, so its space complexity is constant or O(1).
Third Method: using sprintf() and sscanf()
C++
#include <iostream>
using namespace std;
float round( float var)
{
char str[40];
sprintf (str, "%.2f" , var);
sscanf (str, "%f" , &var);
return var;
}
int main()
{
float var = 37.66666;
cout << round(var);
return 0;
}
|
Output:
37.67
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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
03 May, 2023
Like Article
Save Article