Velocity Reviews > C++ > Re: Round to significant figures (C++)

Re: Round to significant figures (C++)

Alf P. Steinbach
Guest
Posts: n/a

 05-01-2006
* 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?