I'm trying to add commas to the following line of code:
Console.WriteLine(String.Format("{0, 8} {1,8} {2,8}", number, square,
cube));
How does one use alignment formatting in conjunction with adding commas?
It's this way
{0,8:N2}
N2 will format with comma based on locale.
Output sample could be useful... This: String.Format("{0, 8}, {1,8}, {2,8}", number, square, cube)); ?
Or you are looking for Number formatting that has thousands separator? Than you need to specify desired CultureInfo as first argument of the String.Format.
Try adding in the commas to the numbers before performing the alignment formatting (modifying based on your locale/culture, if necessary):
Console.WriteLine(
String.Format("{0, 8} {1,8} {2,8}",
number.ToString("#,0"),
square.ToString("#,0"),
cube.ToString("#,0")
)
);
And as Jeff points out in his comment below, you can also accomplish this by including the comma formats inline with the alignment formatting (the first part of each format block gives the alignment, the second part formats the string):
Console.WriteLine("{0,8:#,0} {1,8:#,0} {2,8:#,0}", number, square, cube);
Related
Is there a way to perfectly align two strings in C#?
I am trying to align the string "CBI" with "Central Bureau of Investigation" and I want both strings to occupy 35 characters. I use the function
string.Format("{0,-35}", str);
to format both strings. But they do not appear to be aligned properly. Does it have something to do with the font settings?
I have to use these strings in a chart in excel and they have to occupy the same width on the screen
Yes there is PadLeft and PadRight
str.PadLeft(35);
str.PadRight(35);
str = "BBQ and Slaw";
Console.WriteLine(str.PadLeft(15)); // Displays " BBQ and Slaw".
Console.Write(str.PadRight(15)); // Displays "BBQ and Slaw ".
Side Note from documentation:
However, if totalWidth is less than the length of this instance, the method returns a reference to the existing instance
Basically if your length is less than the length of the string then an reference of the existing string is returned
If EvenMcDonnal wishes to include this in an answer I'll gladly remove it from my answer.
You can find a list of MonoSpaced fonts you can use here
I find that I am never satisfied by monospaced fonts, so I use character padding with a micro-space character (about 1 pixel wide) (char)0x200A to line things up. This is especially useful when simulating column alignment with a list of strings. The most flexible method is to use a while loop comparing string pixel widths and adding the space character until the match. I use System.Windows.Forms.TextRenderer.MeasureText() with a NoPadding flag and just to be save, an initial size of int.MaxValue, then check the Width parameter of System.Drawing.Size. If you feed in any Font in the MeasureText constructor, it works with any font.
According to the following article, if you want to format the max number of decimal places to say 4, but have it chop off trailing zeros 0, you use something like this:
columns.Bound(p => p.Rate).Width(52).Format("{0:####.####}")
http://www.csharp-examples.net/string-format-double
But it doesn't remove the trailing zeros. I need to really save space in this grid, it has like over 10 rate columns that need to be displayed. In most cases the rates only go to 2 or 3 places, but a few of them need 4.
Steve
There is nothing wrond with your formating.
It should have been working for your case, unless you send your decimal values already formatted (i.e. converted into string)
I am writing C# code
Console.Write("{0,-25}", company);
In above code what does this "{0,-25}" thing mean?
You mention it's hard to see what it does: that's because it adds spaces and those are difficult to see in the console. Try adding a character directly before and after the output so you can more clearly see the space, like the examples below:
This
Console.WriteLine("[{0, -25}]", "Microsoft"); // Left aligned
Console.WriteLine("[{0, 25}]", "Microsoft"); // Right aligned
Console.WriteLine("[{0, 5}]", "Microsoft"); // Ignored, Microsoft is longer than 5 chars
Will result in this (with spaces)
[Microsoft ]
[ Microsoft]
[Microsoft]
Which looks like this in the console window:
Read about string formatting on MSDN, specifically composite formatting. The '-25;' specifies the alignment component.
Alignment Component The optional alignment component is a signed
integer indicating the preferred formatted field width. If the value
of alignment is less than the length of the formatted string,
alignment is ignored and the length of the formatted string is used as
the field width. The formatted data in the field is right-aligned if
alignment is positive and left-aligned if alignment is negative. If
padding is necessary, white space is used. The comma is required if
alignment is specified.
That 'thing' is a composite formatting string. See the remarks here and this article here.
It is used for alignment.
Check this so that you can get
Console.Write("Company = |{0,-25}|", company);
string company1="ABC Inc";
string company2="XYZ International Inc";
Console.Write("{0,-10}", company1);//o/p [ABC Inc...]
Console.Write("{0,10}", company1);o/p [...ABC Inc]
Console.Write("{0,-10}", company2);o/p [XYZ International Inc]
//In the first Write(),output is LEFT justified in an output field width of 10
//In second Write(), output is RIGHT justified in an output field width of 10
//In the third Write(), output width is ignored , since the company2 name has more than 10 characters.
I am formatting the currency using Tostring() method i m using following syntax
ToString('##.##') it is working perfectly but in case of round number it remove last 2 zero
like for 100 it does not show 100.00 is shows 100.
how can i format in that way means
input desired output
100 100.00
100.10 100.10
Try "##.00" instead.
That will force two digits after the decimal separator.
You can also use ToString("C") to use the culture specific format in Windows directly.
First google result.
String.Format("{0:C}", x.ToString());
http://www.howtogeek.com/howto/programming/format-a-string-as-currency-in-c/
You can use :
.ToString("C")
Hope it helps.
Also, if you don't want the currency sign ($ in the US) added that "C" gives, you can also use "F2", which is "fixed number with 2 decimal places". It also has the advantage of giving you a thousands separator when you results go over 1,000.00.
This might help. Might be more than you need, but it takes globalization into account which might be necessary. "C" is also a short-cut currency format string that might get you further along.
Im new to C# programming. Can someone please explain the following code:
Console.WriteLine( "{0}{1,10}", "Face", "Frequency" ); //Headings
Console.WriteLine( "{0,4}{1,10}",someval,anotherval);
I understand that this prints two columns of values with the headings given, and {0} refers to the first argument given. But what is the meaning of the format strings of the form {x,y} ?
It adds padding to the left. Very useful for remembering the various string formatting patterns is the following cheat sheet:
.NET String.Format Cheat Sheet
Positive values add padding to the left, negative add padding to the right
Sample Generates
String.Format("[{0, 10}]", "Foo"); [∙∙∙∙∙∙∙Foo]
String.Format("[{0, 5}]", "Foo"); [∙∙Foo]
String.Format("[{0, -5}]", "Foo"); [Foo∙∙]
String.Format("[{0, -10}]", "Foo"); [Foo∙∙∙∙∙∙∙]
When you see {x,y}, x represents the argument's index and y the alignment, as specified here. The complete syntax is the following:
{index[,alignment][:formatString]}
This is a padding value...if the argument isn't the length that is specified, it puts spaces in.
E.g. if you had {0,10} and the argument for {0} was "Blah", the actual value printed would be "Blah<SPACE><SPACE><SPACE><SPACE><SPACE><SPACE>"...Blah, with 6 extra spaces to make up a string of 10 length
ps - not sure how to put actual spaces in...need to look up SO faq no doubt