## 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]; double temp = 0;
int lognum = 0;
std::string formatbuff;
if(sigfig <= 0 || num == 0) return num;
temp = int(num);
if(temp * -1 > 0) temp *= -1;
lognum = (int)log10(temp); ++lognum; sigfig -= lognum;
if(sigfig < 0) sigfig = 0;
formatbuff = "%";
itoa(lognum, buff, 10); formatbuff += buff;
formatbuff += ".";
itoa(sigfig, buff, 10);
formatbuff += buff;
formatbuff += "f";
sprintf(buff, formatbuff.c_str(), num);
return atof(buff);}