Re: Round to significant figures (C++)

Discussion in 'C++' started by Alf P. Steinbach, May 1, 2006.

  1. * Phil Cairns:
    > I've searched for this one, really I have ...
    >
    > I have the following C++ function that rounds a double to an integer
    > with a given number of significant figures. For instance, rounding 1248
    > to 3 signficant figures gives 1250. Rounding 123456789 to 3 significant
    > figures gives 123000000.
    >
    > int setSigFig(double dVal, int nFigs)
    > {
    > int nSize = (int)log10(dVal) - nFigs + 1;
    > if (nSize <= 0)
    > {
    > return (int)dVal;
    > }
    > int nFactor = (int)pow(10.0, nSize);
    > return ((int)(dVal / nFactor)) * nFactor;
    > }
    >
    > There has to be a more efficient way of doing this. Anyone?


    You have limited the function result to the range of int, so I suggest
    limiting the argument to the same range...

    Here's a starting point (yes, it works):

    int firstNDigitsOfPositive( int x, int nDigits )
    {
    assert( x >= 0 && nDigits > 0 );

    IntDigits digits( x );
    int const iHighestZero = (digits.n() - 1) - nDigits;

    if( iHighestZero >= 0 && digits.at( iHighestZero ) >= 5 )
    {
    ++digits.at( iHighestZero + 1 );
    }
    for( int i = iHighestZero; i >= 0; --i )
    {
    digits.at( i ) = 0;
    }
    return digits.intValue();
    }

    where IntDigits is a class you have to define; it's probably also a good
    idea to define one or more wrappers for this function.


    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is it such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet and in e-mail?
    Alf P. Steinbach, May 1, 2006
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Steve
    Replies:
    5
    Views:
    42,649
    Steve
    May 17, 2004
  2. Jeremy Watts

    more than 16 significant figures

    Jeremy Watts, Jul 4, 2005, in forum: Java
    Replies:
    32
    Views:
    1,295
    Tom N
    Jul 15, 2005
  3. Harold

    Significant figures calculation

    Harold, Jun 24, 2011, in forum: Python
    Replies:
    16
    Views:
    1,185
  4. Max Williams
    Replies:
    6
    Views:
    111
    Rob Biedenharn
    May 16, 2009
  5. SMH
    Replies:
    0
    Views:
    213
Loading...

Share This Page