How to modify the precision of floating point numbers in C++

2 Answers

0 votes
#include <iostream>
#include <vector>
#include <cmath>

int main() {
    std::vector<double> v = {123.988, 3.14, 31.123499, 0.15, 0.0000134, 200};

    for (auto &i : v) {
        std::cout << std::fixed << std::ceil(i) << " ";
    }
    std::cout << "\n";

    for (auto &i : v) {
        std::cout << std::fixed << std::floor(i) << " ";
    }
    
    return 0;
}




/*
run:

124.000000 4.000000 32.000000 1.000000 1.000000 200.000000 
123.000000 3.000000 31.000000 0.000000 0.000000 200.000000 

*/

 



answered May 17, 2021 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <cmath>

int main() {
    std::vector<double> v = {123.988, 3.14, 51.123499, 0.15, 0.0000134, 200};

    for (auto &i : v) {
        std::cout << std::fixed << std::round(i) << " ";
    }
    std::cout << "\n";

    for (auto &i : v) {
        std::cout << std::fixed << std::lround(i) << " ";
    }
    
    return 0;
}




/*
run:

124.000000 3.000000 51.000000 0.000000 0.000000 200.000000 
124 3 51 0 0 200 

*/

 



answered May 17, 2021 by avibootz
...