Formatting a number in c# - c#

I want to seperate a number with commas. I have tried many ways to do it. But didn't work.
Its already converted to a string and now i want to format the "tot".
GetData getData = new GetData();
string tot = Convert.ToString(getData.Total_Extra(month));
string totVal = (tot).ToString("N",new CultureInfo("en-US"));
LB2.Text = tot.ToString();

You can convert your tot string to a numeric value and then use string.Format to get the desired format:
string tot = "19950000";
string output = string.Format("{0:n2}", Convert.ToInt32(tot));
Debug.WriteLine(output); //19,950,000.00 on my machine
or alternatively:
string output2 = Convert.ToInt32(tot).ToString("n2");
These are both culture specific, so might display differently on different users machines (Indian culture will display 1,99,50,000.00 for example).
If you want to force the three digit comma grouping then you can specify a culture to use:
string output2 = Convert.ToInt32(tot).ToString("n2", CultureInfo.CreateSpecificCulture("en-GB"));
//19,950,000.00 on any machine
It sounds like your tot may not be a numeric value, so you should check this before trying to format it:
string tot = "19950000";
int totInt;
if (Int32.TryParse(tot, out totInt))
{
string output = totInt.ToString("n2", CultureInfo.CreateSpecificCulture("en-GB"));
MessageBox.Show(output);
}
else
{
MessageBox.Show("tot could not be parsed to an Int32");
}

Related

How can i create a dynamic string format in C#

I have as input the string format CST-000000 and an integer with value 1
Upon using
string result = string.Format("CST-000000", 1);
the expected result should be CST-000001 instead of CST-000000
How could i create this string format dynamically?
For example
- CST-000 should produce CST-001
- HELLO000 should produce HELLO001
- CUSTOMER0000 should produce CUSTOMER0001
Assuming that:
You receive your format string from somewhere and you can't control what it looks like
Your format string ends with 1 or more zeros
If the format string is e.g. CST-00000 and your value is 123, you want the result to be CST-00123
You can do something like this:
Inspect your format string, and separate out the stuff at the beginning from the zeros at the end. It's easy to do this with Regex, e.g.:
string format = "CST-000000";
// "Zero or more of anything, followed by one or more zeros at the end of the string"
var match = Regex.Match(format, "(.*?)(0+)$");
if (!match.Success)
{
throw new ArgumentException("Format must end with one or more zeros");
}
string prefix = match.Groups[1].Value; // E.g. CST-
string zeros = match.Groups[2].Value; // E.g. 000000
Once you have these, note the "Zero placeholder" in this list of custom numeric format strings -- you can write e.g. 123.ToString("0000") and the output will be 0123. This lets you finish off with:
int value = 123;
string result = prefix + value.ToString(zeros);
See it on dotnetfiddle
String.Format requires a placeholder {n} with a zero-based argument number. You can also add it a format {n:format}.
string result = String.Format("CST-{0:000000}", 1);
You can also use String interpolation
string result = $"CST-{1:000000}"
The difference is that instead of a placeholder you specify the value directly (or as an expression). Instead of the Custom numeric format string, you can also use the Standard numeric format string d6: $"CST-{1:d6}"
If you want to change the format template dynamically, String.Format will work better, as you can specify the format and the value as separate arguments.
(Example assumes an enum FormatKind and C# >= 8.0)
int value = 1;
string format = formatKind switch {
FormatKind.CstSmall => "CST-{0:d3}",
FormatKind.CstLarge => "CST-{0:d6}",
FormatKind.Hello => "HELLO{0:d3}",
FormatEnum.Customer => "CUSTOMER{0:d4}"
};
string result = String.Format(format, value);
Also note that the value to be formatted must be of a numeric type. Strings cannot be formatted.
See also: Composite formatting
It seems .toString("CST-000"), .toString("HELLO000") and so on, does the trick.
ToString and String.Format can do much more than use predefined formats.
For example :
string result = string.Format("CST-{0:000000}", 1);
string result = 1.ToString("CST-000000");
Should both do what you want.
(Of course you could replace "1" by any variable, even a decimal one).

Allow insertion with special characters in database using c#

I need to allow $(dollar) ,(comma) and .(full stop) into database by converting from string to decimal.Below is the way i need to insert into database.But with my current code it is inserting as given below
decimal d = Convert.ToDecimal(value);
drNew[i] = d;
i++;
You can use this to convert from a string with currency symbol to decimal:
var num = decimal.Parse("$25,529.98", NumberStyles.Currency);
You may also pass the culture if you need/want:
var cultureInfo = new System.Globalization.CultureInfo("en-US");
var num = decimal.Parse("$25,529.98", NumberStyles.Currency, cultureInfo);
Try this one,
int number = 1234567890;
Convert.ToDecimal(number).ToString("#,##0.00");
You will get the result 1,234,567,890.00.
Your approach is backwards and not advisable. Have a hidden field that stores the numeric value and a label that displays the formatted string in currency format. Then save the numeric value.

How to make string of specified length from another string c#

For example I have strings like:
"5", "8", "14", "260"
and I want to get result like:
"ST00000005", "ST00000008", "ST00000014", "ST00000260"
result string length is 10 chars. How can I do it?
I would store it as int not as string. Then you can use ToString with the appropriate format specifier D8. That has f.e. the advantage that you can increase the number:
int number = 5;
string result = String.Format("ST{0}", number.ToString("D8"));
or without ToString but only String.Format:
string result = String.Format("ST{0:D8}", number);
Read: Standard Numeric Format Strings especially Decimal ("D") Format Specifier
If you need to convert a string to int use int.Parse or int.TryParse.
For the sake of completeness, if you have to use strings use String.PadLeft(8, '0'):
string numStr = "5";
String result = String.Format("ST{0}", numStr.PadLeft(8, '0'));
int number = 5; // put the number here
string result = $"ST{number:0000000#}";
// Or:
string result = $"ST{number:D8}";
This does exactly what you want.
EDIT: Keep in mind that this is only possible in C#6
You can do this like
string s = "215";
s = s.PadLeft(8, '0').PadLeft(9,'T').PadLeft(10,'S');
Use string.Format() together with a custom format string.

show string in a desire format

I want to show my string in a special format.
For example I have a string like this s = "00012345"; and want to show it in this format 000(123-45)
I use this code for it:
label1.text = string.format("{0,###(###-##)}",s);
But just see this for result: 00012345.
What string formatting should I be using?
As mentioned you can't format an already existing string. First you need to convert the string to an int:
int num = Int32.TryParse(s);
Then you can do the formatting whilst converting it back into a string:
label1.text = num.ToString("000(000-00)");
string s = "00012345";
string s1 = s.Substring(0,3);
string s2 = s.Substring(3,3);
string s3 = s.Substring(6);
s = string.Format("{0}({1}-{2})", s1,s2,s3);

using numbers in a string

Can I use numbers while using String data type?
Sure you can, and if you want to use them as numbers you can parse the string. E.g. for an integer:
string numberAsString = "42";
int numberFromString;
if (int.TryParse(numberAsString, out numberFromString))
{
// number successfully parsed from string
}
TryParse will return a bool telling if the parsing were successful. You can also parse directly if you know the string contains a number - using Parse. This will throw if the string can't be parsed.
int number = int.Parse("42");
You can have numbers in a string.
string s = "123";
..but + will concatenate strings:
string s = "123";
string other = "4";
Debug.Assert(s + other != "127");
Debug.Assert(s + other == "1234");
Numbers can be easily represented in a string:
string str = "10";
string str = "01";
string str = 9.ToString();
However, these are strings and cannot be used as numbers directly, you can't use arithmetic operations on them and expect it to work:
"10" + "10"; // Becomes "1010"
"10" / "10"; // Will not compile
You can easily store numbers as a string:
string foo = "123";
but that only helps you if you actually want numbers in a string. For arithmetic purposes, use a number. If you need to display that later, us a format string.
String number1 = "123456";
keep in mind. using that number for arithmatic purpose, you have to convert that string into proper type like
int number1Converted = Int32.Parse(number1);
int.TryParse(number1 , out number1Converted );
for double
double doubleResult = 0.0;
double.TryParse("123.00", out doubleResult);

Categories