Thread: sig figs BCB

    #1
  1. Bad Andy
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Location
    OH
    Posts
    275
    Rep Power
    12

    sig figs BCB


    I know in console C++ iomanip and setprecision could be used to set the number of significant figures to be displayed. However, this was for use with the cout << operator. How would I make say, a double be rounded to 2 sig figs after the decimal? Is it possible to set the value inside the variable?

    SomeFunction(double) = double

    Or is there another way of formatting numbers? As always, any help is appreciated. Thanks.
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,607
    Rep Power
    4247
    Something like this maybe:
    Code:
    #include <cmath>
    #include <iomanip>
    #include <iostream>
    using namespace std;
    
    double roundit(double val, int places) {
      return (floor(val * pow(10, places) + 0.5) / pow(10, places));
    }
    
    int main(void) {
      double foo = 123.456789;
      double bar = roundit(foo, 2);
      cout << setprecision(10) << foo << " " << bar << endl;
    
      return 0;
    }
  4. #3
  5. Big Endian
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    May 2001
    Location
    Fly-over country
    Posts
    1,172
    Rep Power
    30
    You could still use streams (and iomanip) even if you're not doing a console application:
    Code:
    #include <sstream>
    #include <string>
    using namespace std;
    .
    .
    .
    __fastcall TForm1::TForm1(TComponent* Owner)    : TForm(Owner)
    {
       ostringstream oss;
       string sTest;
    
       oss << "AGibel" << " Testing " << 123;
       sTest = oss.str();
       Edit1->Text = sTest.c_str();
    }
    Another method would be to use the CurrToStrF function for formatting currency:

    CurrencyString = ""; // instead of "$"
    CurrencyFormat = 3;
    NegCurrFormat = 15;
    ThousandSeparator = ''; // instead of ','
    DecimalSeparator = '.';

    double dblValue = 1234.5678;
    Amount->Text = CurrToStrF(dblValue, ffNumber, 2);

    You also might want to look at the sprintf() method of an AnsiString. See page 3 and 4 of the attached document.
    Attached Files
  6. #4
  7. Bad Andy
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2003
    Location
    OH
    Posts
    275
    Rep Power
    12
    OK, thanks. I'll try some of those out.

IMN logo majestic logo threadwatch logo seochat tools logo