0

I was having trouble organizing the output into a console for a project. So I wrote a function to add spaces onto strings to format it correctly. Now I am having trouble with 0's not being the proper length before the decimal and it is breaking the format. How can I change a 0.00 into a 00.00? Here is my current function:

void organize(string n[], double tstData[][COLUMN])
{
    int j = 0;
    string spaces[12] = {" ","  ","   ","    ","     ","      ","       ","        ","         ","          ","           ","            "};

    string holder = "";

    for (int i = 0; i < 40; i++) {
        if (n[i].size() < 17) { 
            j = 17 - n[i].size();   
            j = j - 1;
            holder = n[i];
            holder = holder + spaces[j];
            n[i] = holder;  
        }

        for (j = 0; j < 4; j++) {
            if (tstData[i][j] == 0.00) {
                tstData[i][j] = 00;
            }
        }
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612

2 Answers2

1

Most programming languages don't store the exact digits you provide when setting a variable. Instead, they convert the number you provide into a binary representation of that number. When you print a number out, it is converted to a string. The method for converting a number to a string has no awareness of how you set the value, or the number of digits you provided when you set the number. Any two numbers that are numerically the same will be printed the same way.

If you want to ensure you get at least two digits before the decimal place, try:

if(tstData[i][j]) < 10) cout << "0";
cout << tstData[i][j] << endl;
Anish Goyal
  • 2,799
  • 12
  • 17
  • Is it possible to tell the console a specific place to put the value? If so how do I do it? – Mynameis Ian Mar 25 '17 at 05:20
  • 1
    When you say specific place, do you mean a specific number of sig digits, or specific number of digits to the left of the decimal place? both are possible, but in different ways – Anish Goyal Mar 25 '17 at 05:30
1

I highly suggest using, #include <iomanip>, along with setfill(), setw() and setprecision().

setfill('0') to indicate that you want the unused portions to be filled with 0s

setw(4) to indicate the width of the format (0000)

Then finally, use setprecision(2) to set the precision of the format (00.00)

unjankify
  • 190
  • 9
  • I haven't been able to find a solution yet. Here is a screenshot of the cmd if this can clarify the issue better. http://imgur.com/a/ULtOg – Mynameis Ian Mar 25 '17 at 14:01
  • Have you tried the above? This code should not be implemented in the function described above but rather on the output code – unjankify Mar 25 '17 at 23:13