How to round a float to N decimals in C++

4 Answers

0 votes
#include <iostream>
#include <iomanip>

int main() {
    float number = 82.79521;
 
    std::cout << std::fixed << std::setprecision(2) << number;
}




/*
run:

82.80

*/

 



answered Jul 29, 2022 by avibootz
0 votes
#include <iostream>
#include <iomanip>

int main() {
    float number = 82.73521;
 
    std::cout << std::fixed << std::setprecision(2) << number;
}




/*
run:

82.74

*/

 



answered Jul 29, 2022 by avibootz
0 votes
#include <iostream>
#include <iomanip>

int main() {
    float number = 82.73165;
 
    std::cout << std::fixed << std::setprecision(2) << number;
}




/*
run:

82.73

*/

 



answered Jul 29, 2022 by avibootz
0 votes
#include <iostream>
#include <cmath>

float round_float(float number, unsigned char decimals) {
    float pow_10 = pow(10.0f, (float)decimals);
    
    return round(number * pow_10) / pow_10;
}

int main() {
    float number = 82.73165;
 
    std::cout << round_float(number, 3);
}




/*
run:

82.732

*/

 



answered Jul 29, 2022 by avibootz

Related questions

3 answers 148 views
148 views asked Jul 29, 2022 by avibootz
3 answers 165 views
1 answer 133 views
2 answers 191 views
...