Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

C#  ---  A number formatting question. How to solve remaonder zeros from being dropped.  And output tricks.

Posted on 2005-03-11
8
Medium Priority
?
273 Views
Last Modified: 2010-08-05
Hi everyone,


Please excuse the seemingly "Newbie nature of my questions.  I am very new to programming, so if you can show things by example code I would greatly appreciate it.  So...

I am passing a "variant array by reference into this function that I didn't write and can't edit.  Anyway when it returns an object[] refererence to a float[] the values contained in these array elements show the following...

FYI "=" doesn't mean in my example that I'm passing the value into the array element but rather showing you what the value of that element is in the debugger.

Array[0] = 1.2567
Array[1] = 1.25
Array[2] = 1.254

etc.

Anyway my problem is that the number of decimal places is not the same!  What I want is an array that contains the following using the example above..

Array[0] = 1.2567
Array[1] = 1.2500
Array[2] = 1.2540

etc.

This must obviously be based on which ever element in the array has the largest number of decimal places and then making the rest adhere to that.  This is because the array that come back to us from the function will always be giving an array with different MAX decimal places.  Can't tell how many before hand etc.


My questions are as follows...

1)  I know the values are the same but if I wanted to loop thru these returned arrays and print out the values to a CSV delimited text file, I would like the number of decimal places equal.  Can someone show me with a code example how to do this?  Remember that every call to this function/method will result in any number of MAX number of decimal places.

2)  Also is there any way to have the float array identify the largest number of decimals it contains and display the rest to match this with remainder zero's?  Should I copy this float array to a string array first or is this an uneeded step.  The goal is to eventually print these values to a CSV text file.

3)  If I had separate arrays which represent "columns" of data  For example, ArrayCustNum[], ArrayCustName[], ArrayCustCountry[]  And I wished to print them out to a comma separated/Delimited text file.  Is it best to just loop thru the arrays and print to the text file line by line (do it manually) or is there a trick to quickly do this....I don't know "PrintTo/Convert to CSV file with these arrays in this order..." or something requiring 2 or 3 lines of code.

4)  Lastly I want a method to select a path based on the first charater of a file name.  Is there a trick (once a root directory is decided upon) to have a text file thrown/created/saved into alphabetised sub-folders?  For example the sub folders might look like this...

"$%" folder that gets any file named with name that begins with a symbol (non letter or number char) charater
"1-9" folder that gets any file named with a name that begins with a number character

then

"A" folder
"B" folder
"C" folder
....
"Z" folder
etc...



I wish to thank you for your generous help in advance.  I hope this question isn't too long or too involved.



Regards,


Dynotoe
0
Comment
Question by:Dynotoe
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
8 Comments
 
LVL 4

Expert Comment

by:jaynus
ID: 13519022
1.) Convert it to Strings and check lengths to append delimiting 0's. Ex:

-------------------------------------------------
int DigitsWanted = 6; // This is the number of digits we want in our displayed str's
string TempConversionString;  // Temporary string used for conversion, appending, and output.
float TestArray[] = { 1.2567, 1.2510, 1.2500, 1.2000, 1.0000 } // declare our test array

for(int stepCount = 0;stepCount<TestArray.Length;stepCount++) { // Loop through it
     TempConversionString = Convert.ToString(TestArray[stepCount]);  // Convert the float to a string
     if(TempConversionString.Length < 6) {  // If the string length is less than the 6 characters we want to display, append 0's
          if(TempConversionString.IndexOf(".") < 0) TempConversionString += "."; // If it doesnt have a ., Slap a dot on it.
         
          // Below, we loop through each digit after the length until we hit our desired digits.
          for(int digitCount = TempConversionString.Length;digitCount<DigitsWanted;digitCount++) TempConversionString += "0";
          Debug.WriteLine(TempConversionString);
     }
}
-------------------------------------------------

2.) Loop through the contents of the Array again and check which one is the longest string.  If you need an example of that too, let me know.

3.) I do not know of any "multiple array csv output". Though, I can loop through the values and print them out in comma delimited format in 5-10 lines of code, so it seems inconsequential. Let me know if you need an example of that too :)

4.) For all of this, you can just check the first character of the string of the file and dump it accordingly.  If you want it a little smoother, you could impliment an instance of one of the Sorting Interfaces. Though its sort of unneeded, it would sort your array by however you want.  I have examples of different implimentations if you would like.

Hope that helps!!

-jaynus
0
 

Author Comment

by:Dynotoe
ID: 13519591


Hi again!

Sorry about these follow-up questions..  ;(


I fully understand to copy/convert a float[] to a string[] then loop thru it and fix things and then fianally print it out to a CSV file.  However when doing so there is a automatic conversion going on to string I think.  But I assume this creation of a separate array is necessary?  It would be great if I could affect the auto conversion to string instead.

As far as ...
"2.) Loop through the contents of the Array again and check which one is the longest string.  If you need an example of that too, let me know."

Looping thru the string array looking at the length i.e., the longest string....How do I do this if I just want the longest decimal place only of the decimal portion not the whole/integer portion of the string??  This is because the integer portion of the number is variant.  I think your first answer assumes "int DigitsWanted = " is known before hand.  Then as you suggest to loop thru the array first to get this value but it is looking a the whole string length as apposed to just the decimal part of the string.  See what I mean.

FYI these arrays represent the price history of financial instuments i.e., stocks, currencies, futures so the integer string length varies.  For example lets look at a stock xyz....

array[0] = 97.5
array[1] = 98.57
array[2] = 103.88
array[3] = 99.2    etc...

See what I mean...


Best,

Dynotoe

0
 
LVL 4

Accepted Solution

by:
jaynus earned 2000 total points
ID: 13519744
As far as I know, looping through conversion arrays etc are the only ways to do something like this as far as I know.  We could stick it all in maybe 2 loops, to keep execution time down. As far as automated methods to do such, I don't believe there is really anything out there for that.

2.) Loop through it *before* you do your appendaging(rofl, pun!) and get the DigitsWanted field.
So the steps would look like this.

1. ) Convert it all into strings and dump that into a string[] Array, and check the digits while we do this in the example below.
2. ) Now that they are all strings and we have our maxLength, loop through it once more and dump our terminating 0's

---------------------
float TestArray[] = { 1.2567, 1.2510, 1.2500, 1.2000, 1.0000, 1.1111111 }

int DigitsWanted = 0;
string TempConversionString[] = new string[TestArray.Length];

// Dump each string into the associated position in our temp array, and check lengths.
for(int stepCount = 0;stepCount<TestArray.Length;stepCount++) { // Loop through it
     TempConversionString[x] = Convert.ToString(TestArray[stepCount]);  // Convert the float to a string

     // Below, we check the length of the string *after* the decimal place. If its longer than anything previous, set it.
     if(TempConversion.Substring(TempConversion.IndexOf(".")+1, TempConversion.Length).Length > DigitsWanted)
          DigitsWanted = TempConversion.Substring(TempConversion.IndexOf(".")+1, TempConversion.Length).Length;
}

// Now we rinse and repeat and append our 0's.
for(stepCount = 0;stepCount<TempConversionString.Length;stepCount++) { // Loop through it
     if(TempConversion.Substring(TempConversion.IndexOf(".")+1, TempConversion.Length).Length < DigitsWanted) {  
          if(TempConversionString[x].IndexOf(".") < 0) TempConversionString += ".";

          // Below, we loop through each digit after the length until we hit our desired digits.
          for(int digitCount = TempConversion.Substring(TempConversion.IndexOf(".")+1, TempConversion.Length).Length; digitCount<DigitsWanted;digitCount++)
               TempConversionString += "0";
     }
     Debug.WriteLine(TempConversionString[x]);
}

---------------------
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

Author Comment

by:Dynotoe
ID: 13519967
"As far as I know, looping through conversion arrays etc are the only ways to do something like this as far as I know.  We could stick it all in maybe 2 loops, to keep execution time down. As far as automated methods to do such, I don't believe there is really anything out there for that."


Yeah I wasn't very clear in that paragraph as far as what I was refering to.  What I meant by auto conversion was that I think (and maybe wrong..very good chance lol) when you write line by line to a text file, isn't there a automatic conversion to string using streamwriter?  Anyway that is what I was refering to.


So....

Great solution Jaynus!  Very generous answer and I am truely greatful.

Thanks once again.

Bye for now from Boston.  :)


Best,

Dynotoe
0
 
LVL 4

Expert Comment

by:jaynus
ID: 13520000
I wouldnt trust an automagic conversion from a stream anyways :p
0
 

Author Comment

by:Dynotoe
ID: 13521337
With Jaynus great guidance and some fixes I came up with this that compiles and works like a charm if people want it...

Jaynus what do you think?



                  double[] TestArray = new double[4];
                  TestArray[0] = 1.25;
                  TestArray[1] = 1.1;
                  TestArray[2] = 12678.25678;
                  TestArray[3] = 10.253;

                  int DigitsWanted = 0;
                  string[] TempConversionString = new string[TestArray.Length];

                  // Dump each string into the associated position in our temp array, and check lengths.
                  for(int x = 0; x < TestArray.Length; x++)
                  { // Loop through it
                        TempConversionString[x] = Convert.ToString(TestArray[x]);  // Convert the float to a string
                        int DecimalStringLength = TempConversionString[x].Split('.')[1].Length;

                        // Below, we check the length of the string *after* the decimal place. If its longer than anything previous, set it.
                        if(DecimalStringLength > DigitsWanted)
                              DigitsWanted = DecimalStringLength;
                  }

                  // Now we rinse and repeat and append our 0's.
                  for(int i = 0; i < TempConversionString.Length; i++)
                  { // Loop through it
                        int DecimalStringLength = TempConversionString[i].Split('.')[1].Length;

                        if(DecimalStringLength < DigitsWanted)
                        {  
                              if(TempConversionString[i].IndexOf(".") < 0) TempConversionString[i] += ".";

                              // Below, we loop through each digit after the length until we hit our desired digits.
                              for(int digitCount = DecimalStringLength; digitCount < DigitsWanted; digitCount++)
                                    TempConversionString[i] += "0";
                        }
                  }

Dynotoe
0
 
LVL 4

Expert Comment

by:jaynus
ID: 13521342
:D
0
 

Author Comment

by:Dynotoe
ID: 13521530


Oooops....

Stick this line....

if(TempConversionString[x].IndexOf(".") < 0) TempConversionString[x] += ".";

in between these 2 lines....

TempConversionString[x] = Convert.ToString(TestArray[x]);  // Convert the float to a string
(here)
int DecimalStringLength = TempConversionString[x].Split('.')[1].Length;

Just in case lol

Dynotoe
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question