How to convert a double number to 3 decimal places number in C++

3 Answers

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

int main() 
{ 
    double n = 89.560873;

    // Set precision to show 3 digits after the decimal
    std::cout << std::fixed << std::setprecision(3) << n << std::endl;
}



/*
run:
 
89.561
 
*/

 



answered 3 days ago by avibootz
edited 3 days ago by avibootz
0 votes
#include <iostream>
#include <cmath>
 
int main() 
{ 
    double n = 89.560873;
 
    // Round to 3 decimal places
    n = std::round(n * 1000) / 1000;

    std::cout <<  n << std::endl;
}
 
 
 
/*
run:
  
89.561
  
*/

 



answered 2 days ago by avibootz
0 votes
#include <iostream>
#include <cmath>

/**
 * Rounds a double to a specified number of decimal places.
 *
 * return the rounded number
 */
double roundTo(double n, int roundto) {
    roundto = pow(10, roundto);
    
    return std::round(n * roundto) / roundto;
}

int main() 
{ 
    double n = 89.560873;
 
    // Round to 3 decimal places
    n = roundTo(n, 3);

    std::cout <<  n << std::endl;
}
 
 
 
/*
run:
  
89.561
  
*/

 



answered 2 days ago by avibootz
edited 2 days ago by avibootz

Related questions

2 answers 58 views
3 answers 256 views
1 answer 55 views
1 answer 111 views
2 answers 111 views
...