13,145,794 members (59,595 online)
alternative version

#### Stats

55.5K views
20 bookmarked
Posted 5 Dec 2002

# A Strategy for Displaying Numeric Data with Significant Figures

, 5 Dec 2002
 Rate this:
A strategy for displaying numeric data with significant figures using Log10.

## Introduction

Problem: Some times numeric data, for example floats and doubles, needs to be displayed with a certain amount of decimal precision and at times with a given amount of significant figures.

For example:

```4.5568 displayed with 2 Significant Figures is: 4.6
0.0221 displayed with 3 Significant Figures is: 0.022
5.9 displayed with 1 Significant Figures is: 6```

Strategy: Using the `log10` function we can calculate the number of digits for the integer part of the number we are manipulating. The decimal part of the number can be displayed properly with a `sprintf` call or something similar as we can see in our function below. This solution also rounds the final number, which is usually desirable when displaying significant figures.

```double CalculateSigFig(double num, int sigfig)
{
char buff[128];//temp buffer
double temp = 0;
int lognum = 0;
std::string formatbuff;//format string

if(sigfig <= 0 || num == 0)//damage control
return num;

temp = int(num);
if(temp * -1 > 0)//check for negative numbers
temp *= -1;

lognum = (int)log10(temp);//get significant digits of integer part of num
sigfig -= lognum;//subtract for decimal precision calculation

if(sigfig < 0)//check for negative results
sigfig = 0;

//construct format string
formatbuff = "%";
itoa(lognum, buff, 10);//convert lognum to int
formatbuff += buff;
formatbuff += ".";
itoa(sigfig, buff, 10);
formatbuff += buff;
formatbuff += "f";
//end construct format string

//use format string to get desired results
sprintf(buff, formatbuff.c_str(), num);

return atof(buff);//return double converted from string
}```

A list of licenses authors might use can be found here

## Share

 United States
No Biography provided

## You may also be interested in...

 Pro Pro

 First Prev Next
 C# Version of Significant Figures or Significant Digits Leonard Lee20-Apr-08 21:26 Leonard Lee 20-Apr-08 21:26
 Another strategy ? Stlan9-Dec-02 3:29 Stlan 9-Dec-02 3:29
 _fcvt Tim Smith7-Dec-02 2:41 Tim Smith 7-Dec-02 2:41
 Re: _fcvt zarzor7-Dec-02 11:20 zarzor 7-Dec-02 11:20
 Or what... zarzor6-Dec-02 13:22 zarzor 6-Dec-02 13:22
 What does that give me over... Nitron6-Dec-02 10:33 Nitron 6-Dec-02 10:33
 Doesn't work KevinHall6-Dec-02 6:19 KevinHall 6-Dec-02 6:19
 Does it work? eddie.breeveld6-Dec-02 5:20 eddie.breeveld 6-Dec-02 5:20
 Last Visit: 31-Dec-99 18:00     Last Update: 22-Sep-17 17:15 Refresh 1