using System; using System.Globalization; using System.Text; public class NumParsingApp { public static void Main(string[] args) { string u = "AA -1,234,567.890 "; NumberFormatInfo ni = new NumberFormatInfo(); ni.CurrencySymbol = "AA"; double h = Double.Parse(u, NumberStyles.Any, ni); Console.WriteLine("h = {0:F}", h); } }
Software Development
software development notes, main category for Cs, Java, and other programming experiences.
{0,4} {1,4} {2,4} {3,4} {4,4}
using System;
public class MainClass {
public static void Main() {
Random rnd = new Random();
int[,] m = new int[3, 5];
for (int i = 0; i < m.GetLength(0); i++)
for (int j = 0; j < m.GetLength(1); j++)
m[i, j] = rnd.Next(1000);
for (int i = 0; i < m.GetLength(0); i++)
Console.WriteLine("{0,4} {1,4} {2,4} {3,4} {4,4}", m[i, 0], m[i, 1], m[i, 2], m[i, 3], m[i, 4]);
}
}
[/csharp]
|{0,10:X}|{1,10}|{2:X}|{3}|
public class MainClass { public static void Main() { int i = 250662; string s = string.Format("|{0,10:X}|{1,10}|{2:X}|{3}|", i, i, i, i); } }
left justify and align a set of strings to improve the appearance of program output
using System;
class Class1 {
public static void Main(string[] args) {
string[] names = {“CA “,” SA”,”J A”,”SA”,” SA “};
foreach (string s in names) {
Console.WriteLine(“This is the name '{0}' before”, s);
}
string[] sAlignedNames = TrimAndPad(names);
foreach (string s in sAlignedNames) {
Console.WriteLine(“This is the name '{0}' afterwards”, s);
}
}
public static string[] TrimAndPad(string[] strings) {
string[] stringsToAlign = new String[strings.Length];
for (int i = 0; i < stringsToAlign.Length; i++) {
stringsToAlign[i] = strings[i].Trim();
}
int nMaxLength = 0;
foreach (string s in stringsToAlign) {
if (s.Length > nMaxLength) {
nMaxLength = s.Length;
}
}
for (int i = 0; i < stringsToAlign.Length; i++) {
stringsToAlign[i] =
stringsToAlign[i].PadRight(nMaxLength + 1);
}
return stringsToAlign;
}
}
[/csharp]
Control the width
using System; public class TestConsoleApp { public static void Main(string[] args) { Console.WriteLine(" {0,-10}{1,-3}", "Name", "Salary"); Console.WriteLine("{0,-10}{1,6}", "Bill", 123456); Console.WriteLine("{0,-10}{1,6}", "Polly", 7890); } }
The comma (,M) determines the field width and justification.
using System; public class TestConsoleApp { public static void Main(string[] args) { Console.WriteLine( "{0,5} {1,5}", 123, 456); // Right-aligned Console.WriteLine( "{0,-5} {1,-5}", 123, 456); // Left-aligned Console.WriteLine( "{0,-10:D6} {1,-10:D6}", 123, 456); } }
Use string.Format to format integer
using System; public class TestConsoleApp { public static void Main(string[] args) { string s = string.Format("123"); string t = string.Format("{0}", 123); string u = string.Format("{0:D3}", 123); Console.WriteLine(s); Console.WriteLine(t); Console.WriteLine(u); } }