Set Precision in C++ Builder

Hi,

I've written a program in C++ Builder 6, in order to generate a code for PSpice software. In this code I've used a for loop like this:

for (double i=deltax/2; i<Lx; i=i+deltax)
{
Memo1->Lines->Add("** i= " + (AnsiString)i);

}

deltax and Lx are doubles. My problem is that after some iterations, the value of i increases by a very small extent and this small error is troublesome for me. for example when I expect i=12.08, it says i=12.08000000000001.

As a solution, I want i to have only 2 digits as decimals. How can I write this?
solution 1... work in integers as if *100. Insert the decimal with a custom print routine (cout << value/100 << "." << value % 100;). This keeps your precision pristine internally, so you don't accumulate roundoff errors (important if this is money, for example).

solution 2: just change the print statement. You may want to bump round it (what if you had gotten 12.079999999999999999 instead? you need to bump it up to 12.08 ) first. That looks like std::cout << std::setprecision(2) << value << '\n'; or
if value >= 0
std::cout << std::setprecision(2) << value + 0.001 << '\n';
else
std::cout << std::setprecision(2) << value - 0.001 << '\n';

if I did all that correctly. Hopefully you get the idea.

1
2
3
4
5
6
for (double i=deltax/2; i<Lx; i=i+deltax)
{
    AnsiString temp;
    temp.sprintf("** i= %.2f", i);
    Memo1->Lines->Add( temp );
}


Registered users can post here. Sign in or register to post.