• Welcome to Valhalla Legends Archive.
 

Fancy Formatting C# Lesson #2 of 2

Started by DecA, November 19, 2004, 09:44 AM

Previous topic - Next topic

DecA

                        Fancy Formmating By Deca[xL] 2 of 2
__________________________________________________________________________________

If you are reading this tutorial, I am going to assume you read my introduction that leads up to this tutoial. In the last tutorial we covered some formatting features in the ToString method, and also we covered the basics of hungarian notation. In the last thread there was some qustioning to "Why are you using hungarian notation in a Strongly Typed language?" Well, my reason is, because it can get difficult to identify your variables data types in large complex projects, so that is why I see it to be a good exercise, and good to get used to using it, also, it dosn't hurt anything. But anyways, the main topic we focused on in the last tutorial was converting data types to another desired data type., example:

decimal  mA = 0.123m;
Console.Write(iA.ToString("P"); /*this will take the decimal value(0.123) multiply it by 100, add a Percent sign, and seperate the thousands with commas*/


So lets jump right in and get started. In this code above, you could optionally follow the letter with a number, like so..

mA.ToString("P5");

Rather than displaying this as 12.30 %, it would display as 12.30000 %. See..what your doing by adding this argument is telling it you want it to display 5 decimal spaces rather than the default( 2 ).

The number has a differnt meaning depending on what letter you use. Here is a table showing how each of them handle the number.
__________________________________________________________________________________
Letter   Meaning        Effect of number
__________________________________________________________________________________
C   Currency   Number of decimal places displayed ( default is 2)
D   Decimal      Desired character width of result, padded with zeroes if nessasry.
E   Expontenial   Number of places after the decimal point ( default is 6)
F   Fixed Point   Number of decimal places displayed ( default is 2)
G   General      Desired character width
N   Number      Number of decimal places displayed ( default is 2)
P   Percent      Number of decimal places displayed ( default is 2)
R   RoundTrip   Ignored
X   Hexadeximal   Desired character width of resuly, padded zeroes if necessary
__________________________________________________________________________________

Ok, so there you go, you should take a couple mins. to read and understand that table befor moving on. So now lets make a little program to display a decimal variable with all the formatting specifications allowed for a decimal data type.


using System;


class NumericFormatting
{
static void Main()
{
decimal mA = 12345.345m;
Console.Write("Curreny Formatting: " + mA.ToString("C2"));
Console.Write("Exponetial Formatting: " + mA.ToString("E2"));
Console.Write("Fixed Point Formatting: " + mA.ToSting("F2"));
Console.Write("General Formatting: " + mA.ToString("G2"));
Console.Write("Number Formatting: " + mA.ToString("N2"));
Console.Write("Percent Formatting: " + mA.ToString("P2));

}
}

This should is what you should see in your console when it executes:

Currency Formatting: $12,345.35
Exponential Formatting: 1.23E+004
Fixed Point Formatting: 12345.35
General Formatting: 1.2E+04
Numeric Formatting: 12,345.35
Percent Formatting: 1,234,534.50 %

If you don't see this than you suck, sorry :P

You might have noticed that, the "ToString" method sometimes rounds the numer befor converting it to a string. However, the "ToString" method uses different rounding rules thant the "Round" method. Values exactly between two rounded values are rounded up, for example,  In the NumericForammating program we just made, the number 12345.345 is rounded up to 12345.35 instead of 12345.34, if one of these rounding methods don't work for you, try rounding the number with the "Round" method befor you display it.

Here is a conversion to Hexadecimal using the integer 123456.

iA.ToString("X8");


"ToString" creates the string 00003039. If you indicate a number less tha 4 in this example, the resualtant string will have four characters. These Formatting Specifacations never cause numbers to be truncated because of in sufficient colum width. The worst that can happen with formatting is that precision will be lost, for example...

iA.ToString("E2")


This results in the string "1.23E+004" because you'be specified only teo decimal places.
When displaying multiple numbers with the Console.WriteLine mthod, we've been using string concatenaion like this:

Console.WriteLine("The sum of " + A + " and " + B + " is " + (A + B));


If you want to control the formatting of any of these values, you can use the "ToSring" method to convert the numbers to strings befor concatenation:

Console.WriteLine("The Sum of " + A.ToString("E4") +
       " and " + B.ToString("E4") +
      + is " + (A+B).ToString("E4"));


You might agree that this look pretty messy and not very readable.
The Write && WriteLine methods support an alternative to displaying text and multiple numbers that is based on the concept of formatting string with placeholders where the values of variables are to appear. Here's an equivalant of the first of the two WriteLine calls i just showed you.

Console.WriteLine("The sum of {0} and {1} is {2} " , A, B, A + B);


This is a overload of the WriteLine method.  Four arguments are shown here. The sfirst argument is the formatting string that basiclly contains the text we want to diplay. In this string are the numebers, 0, 1, and 2 enclosed in curly brackets. These numbers in the brackets are place holders. When WriteLine displays the string, the sencond argument to WriteLine ( A  in this case ) is interted at the position of {0}, the third argument ( B ) is inserted at {1} and the fourth argument ( A + B ) is inserted into {2}. The arguments could be numeric variables, sting variables, or any other type of variable or literal. If you want to show curly brackets as part of your formatting sting, use two curly brackets together. The placeholders don;t have to be in numeric order in the formatting strinf, but the numeic order has to correspond to the oreder of the subsequent arguments. Heres a example of what im talking about:

Console.WriteLine("The Sum of {2} and {1} is {0}", A + B, B, A);


The only real rule is that the number of arguments after the formatting string has to be greater or equal to the highest number you use in a placeholder minus 1. Theres no plroblem if you have more arguments than the placeholders would show.


Console.WriteLine(:The sum of {2} and {1} os {0}", A + B, B, A, C);


Notice the extra C variable at the end. It's ignored in this WriteLine call. You can also skip placeholder numbers if you want:


Console.WriteLine("The answer is {0} and nothing but {0}", A);


But this stament is a problem and would rais an exception:


Console.WriteLine("The sum of {0} and {1} is {3}", A, B, A + B);


The highest placeholder is three, this would mean you would need 4 arguments following the the formatting string. Heres the WriteLine statment i showed you earlier using Sting concatenation and explicit calls to ToString to format the numebrs more of  like we want.


Console.WriteLine("The Sum of " + A.ToString("E4") +
       " and " + B.ToString("E4") +
      + is " + (A+B).ToString("E4"));


You could also write this statement using a formatting string:


Console.WriteLine("The Sum of {0} and {1} is {2}",
       A.ToString("E4"), B.ToString("E4"),
       (A + B).ToString("E4"));


Its sitll a mess, but check this out, you can include numeric formatting specifications as part of the formatting string. All the explicit ToString calls are gone:


Console.WriteLine("The sum of {0:E4} and {1:E4} is {2:E4}", A, B, A + B");


Thr placeholder number is simply followed by a colon and then short formatting specifacation string that you would notmally pass to ToString. This is a much more conventional method of doning this rather than the ToString for obvious reasons. In most cases, you really can't predict the character width of diplayed numbers. Depending on its value, and int could need anywhere from 1 to 10 characters if it is a positive, 11 if it is a negative, and 14 if the thousands are sperated.
Here is a example of what not to do when using this method.


Console.WriteLine("{0}{1}{2}{3}", A, B, C, D);


This would cause the numebrs to be all jammed up and hard to read, all you would need to do is, leave spaces between {0} {1} {2} {3} like that.
Sometimes you will have several similar WriteLine statements, and you will want everything arranged in nice neat columns. To indicate a character width for the displayed variable, you can include that, width is called a field, width is a placeholder string. Seperate the placeholder number and the field with a comma:


Console.WriteLine("{0,10} {1,15} {2,10} {3,30}", strB, mA, iC, mD);


The first number is displayed in a field 10 characters wide. The number is right justified in that field. The second variable is a string, it is in a 15 characters wide field, this is how if might look...

85.748      text      80      93713.74   

You can use a negative feild width to make it be left justified in the field.

Your console display should have a width of 80 characters, so its traditional to restrict the entire fotamatting string and fireld width to something fewer than 80 characters. But, if the numbers require more space than the field wifth, they will be given that space.
Ok, lets combine everything i have shown you in this lesson to conclude.

using System;

namespace FancyFormatting
{
class Final
{
static void Main()
{
string strB = "Deca";
decimal mA = 22.55m;
int iC = 122;
decimal mD = 27.35m;
Console.WriteLine("{0,-10} {1,10:C2} {2,10:X5} {3,20:E3}", strB, mA, iC, mD);
int B = Int32.Parse(Console.ReadLine());
}
}


This should display display:

Deca      $22.55      007A      2.735E+001

Ok good job guys!, please excuse the little errors I might have done, i stayed up all night writeing this =(, Yeah...i was bored, but that comes with house arresst, it is currently 6:26am.
Ok, so if anyone has any qustions regarding this lesson, feel free to IM me at xlDECAlx (aim)
I do plan on writeing another tutorial here in the next week or so on Stack and Heap, but yeah, I hope this can help you beginners.

      
   --Deca[xL] of Op Exile@USWest  ;D


Fin

MyndFyre

I still think you should have gone with String.Format instead of Console.WriteLine.  That way people could have known there is a function to create new strings like that.  Console.WriteLine is convenient if you're using a console.  :-P
QuoteEvery generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?

After 3 years, it's on the horizon.  The new JinxBot, and BN#, the managed Battle.net Client library.

Quote from: chyea on January 16, 2009, 05:05 PM
You've just located global warming.

DecA

Yes, that was what i was intending for. I believe people should have a good grip on console apps. befor moving on to Form based projects :P Note: This was intended for beginners

MyndFyre

Quote from: DecA on November 19, 2004, 02:26 PM
Yes, that was what i was intending for. I believe people should have a good grip on console apps. befor moving on to Form based projects :P Note: This was intended for beginners

Note: String.Format works just as well in console apps as it does in Windows apps.  :P
QuoteEvery generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?

After 3 years, it's on the horizon.  The new JinxBot, and BN#, the managed Battle.net Client library.

Quote from: chyea on January 16, 2009, 05:05 PM
You've just located global warming.

DecA

#4
Note: Deca knows this but feels Console.WriteLine is more "newb friendly"   ;D


MyndFyre

Quote from: DecA on November 19, 2004, 03:08 PM
Note: Deca knows this but feels Console.WriteLine is more "newb friendly"   ;D


Brian oliver sucks

Why are you posting off-topic?
QuoteEvery generation of humans believed it had all the answers it needed, except for a few mysteries they assumed would be solved at any moment. And they all believed their ancestors were simplistic and deluded. What are the odds that you are the first generation of humans who will understand reality?

After 3 years, it's on the horizon.  The new JinxBot, and BN#, the managed Battle.net Client library.

Quote from: chyea on January 16, 2009, 05:05 PM
You've just located global warming.


hismajesty

I actually agree with MyndFyre. The name of the lessons are 'Fancy Formatting' not 'C# 101.' It's understood that a user may or may not be advanced in C# when reading this, but that's besides the point, since it's about formatting.