How to round a number 3 significant figures in C++

My goal is very simple I just want to round a number by 3 significant figures

for example if the user inputs:

655900 433.72

rounding it to 3 significant figures should look like : 656000 434

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;

double roundDouble( double x, int n )
{
   stringstream ss;
   ss << scientific << setprecision( n - 1 ) << x; 
   return stod( ss.str() );
}

int main()
{
   cout << roundDouble( 655900.0, 3 ) << "  " << roundDouble( 433.72, 3 ) << '\n';
}


656000  434
Very clever, using the scientific form to force it to show a certain number of digits.
Thank you so much that's exactly what i needed
It's not worth doing it "manually" using <cmath>'s round() function.
I'd like to see the ostream library code that does it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cmath>
using namespace std;

double roundDouble1( double x, int n )
{
   stringstream ss;
   ss << scientific << setprecision( n - 1 ) << x; 
   return stod( ss.str() );
}

double roundDouble2( double x, int n )
{
    int shift = 0;
    bool neg = false;
    if (x < 0.0) {
        x = -x;
        neg = true;
    }
    // normalize
    for ( ; x <  1.0; --shift) x *= 10;
    for ( ; x >= 1.0; ++shift) x /= 10;
    // shift
    for ( ; n > 0; --n, --shift) x *= 10;
    // round
    x = round(x);
    // adjust
    for ( ; shift > 0; --shift) x *= 10;
    for ( ; shift < 0; ++shift) x /= 10;
    return neg ? -x : x;
}

int main()
{
   cout << roundDouble1( 655900.0, 3 ) << "  " << roundDouble1( 433.72, 3 ) << '\n';
   cout << roundDouble2( 655900.0, 3 ) << "  " << roundDouble2( 433.72, 3 ) << '\n';

   cout << roundDouble1( 1.0, 3 ) << "  " << roundDouble1( 0.0072123, 3 ) << '\n';
   cout << roundDouble2( 1.0, 3 ) << "  " << roundDouble2( 0.0072123, 3 ) << '\n';

   cout << roundDouble1( -655900.0, 3 ) << "  " << roundDouble1( -433.72, 3 ) << '\n';
   cout << roundDouble2( -655900.0, 3 ) << "  " << roundDouble2( -433.72, 3 ) << '\n';

   cout << roundDouble1( -1.0, 3 ) << "  " << roundDouble1( -0.0072123, 3 ) << '\n';
   cout << roundDouble2( -1.0, 3 ) << "  " << roundDouble2( -0.0072123, 3 ) << '\n';
}

Last edited on
Topic archived. No new replies allowed.