parsing a string into int/long using custom format strings - c#

In C#.Net, here's a simple example of how to format numbers into strings using custom format strings:
(example taken from: http://www.csharp-examples.net/string-format-int/)
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"
Is there a way to convert this formatted string back into a long/integer ? Is there someway to do this :
long PhoneNumber = Int32.Parse("89-5871-2551", "{0:##-####-####}");
I saw that DateTime has a method ParseExact which can do this work well. But I did not see any such thing for int/long/decimal/double.

You can regex out all of the non numeric numbers, and what you're left with is a string of numbers that you can parse.
var myPhoneNumber = "89-5871-2551";
var strippedPhoneNumber = Regex.Replace(myPhoneNumber, #"[^\d]", "");
int intRepresentation;
if (Int32.TryParse(strippedPhoneNumber, out intRepresentation))
{
// It was assigned, intRepresentation = 8958712551
// now you can use intRepresentation.
} else {
// It was not assigned, intRepresentation is still null.
}

Well, you can always do
long PhoneNumber = Int32.Parse("89-5871-2551".
Replace(new char[]{'-','+',whatever..}).Trim());
By the way, considering that you're parsing a string received from some IO, I would suggest to use more secure (in terms of conversion) Int32.TryParse method.
The way like you described doesn't actually exist.

Just Regex out all of the non-numeric characters, then parse that string.

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).

How to remove DateTime substring from string

I have a bunch of strings, some of which have one of the following formats:
"TestA (3/12/10)"
"TestB (10/12/10)"
The DateTime portion of the strings will always be in mm/dd/yy format.
What I want to do is remove the whole DateTime part including the parenthesis. If it was always the same length I would just get the index of / and subtract that by the number of characters up to and including the (. But since the mm portion of the string could be one or two characters, I can't do that.
So is there a way to do a .Contains or something to see if the string contains the specified DateTime format?
You could use a Regular Expression to strip out the possible date portions if you can be sure they would consistently be in a certain format using the Regex.Replace() method :
var updatedDate = Regex.Replace(yourDate,#"\(\d{1,2}\/\d{1,2}\/\d{1,2}\)","");
You can see a working example of it here, which yields the following output :
TestA (3/12/10) > TestA
TestB (10/12/10) > TestB
TestD (4/5/15) > TestC
TestD (4/6/15) > TestD
You could always use a regular expression to replace the strings
Here is an example
var regEx = new Regex(#"\(\d{1,2}\/\d{1,2}\/\d{1,2}\)");
var text = regEx.Replace("TestA (3/12/10)", "");
Use a RegEx for this. I recommend:
\(\d{1,2}\/\d{1,2}\/\d{1,2}\)
See RegExr for it working.
Regex could be used for this, something such as:
string replace = "TestA (3/12/10) as well as TestB (10/12/10)";
string replaced = Regex.Replace(replace, "\\(\\d+/\\d+/\\d+\\)", "");
If I'm understanding this correctly you want to just acquire the test name of each string. Copy this code to a button click event.
string Old_Date = "Test SomeName(3/12/10)";
string No_Date = "";
int Date_Pos = 0;
Date_Pos = Old_Date.IndexOf("(");
No_Date = Old_Date.Remove(Date_Pos).Trim();
MessageBox.Show(No_Date, "Your Updated String", MessageBoxButton.OK);
To sum it up in one line of code
No_Date = Old_Date.Remove(Old_Date.IndexOf("(")).Trim();

Format numeric string with comma separator for indian numbering system

I have a number value in string as
string strNum = "12345678.90";
I want to format it with comma separator using regex in String.Format()
On using "{0:n0}" format in
String.Format("{0:n0}", Convert.ToDouble(strNum));
it is giving me output as "12,345,679"
Instead of this i want output as "1,23,45,678.90". After thousand's place i want comma separator after 2 digits each for lakhs, crores and so on
How can this be achieved?
var s = String.Format(new CultureInfo( "en-IN", false ), "{0:n}", Convert.ToDouble("12345678.90"));
For such a typical way I would write a specialized function that transforms a number into the string you propose.
I even would suggest to make the item a class, having the value represented as float or by different items like lakhs, crores etc.
And then make a ToString method to output it the way you want.
Example (not tested):
class SpecialNumber
{
int _lakhs;
int _crores;
int _another_unit;
int _rest;
public SpecialNumber(int lakhs, int crores, int another_unit, int rest)
{
_lakhs = lakhs;
_crores = crores;
_another_unit = another_unit;
_rest = rest;
}
public string ToString()
{
// Check for exact formatting.
return String.Format("{0:2},{1:2},{2:3}.{0:2}",
_laksh, _crores, _another_unit, _rest);
}
My best bet would be to use the String.Format along with '#' as such:
String.Format(0:##,##,##,##,##,###.##)
The '#' is a digit placeholder and will not show a zero (or anything else) if the number is not large enough.
See MSDN custom numeric format strings for further details.
you seem to format according to hindi culture.
so set your culture, or provide the culture to String.Format, like
String.Format(CultureInfo.GetCultureInfo( "<yourculture>" ), "{0:n}", Convert.ToDouble(strNum));
With this code you can change an amount string to Indian standard comma separated value; use culture "hi-IN" and the format "{0:#,0.00}"
here strNum is my string value amount.
string.Format( System.Globalization.CultureInfo.CreateSpecificCulture("hi-IN"), "{0:#,0.00}", Convert.ToDouble(strNum)

C# - How to format datetime to remove trailing zeros

I'm setting up an orchestration class that handles multiple actions as one big transaction. For each of these transactions I give them the same time-stamp instantiated at the beginning of the orchestration.
I user the following line:
var transactionTimestamp = DateTime.UtcNow.ToString("o");
I have a constraint in the system that dictates that the time stamp cannot have any trailing zeros.
For example:
2013-06-26T19:51:38.0083980Z //bad
2013-06-26T19:51:38.008398Z //good
2013-06-26T19:51:38.0083988Z //good
The built-in DateTime format "o" is comparable to the custom format of: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK". If you just use that format, but replace the lower-case f's with upper case ones, there will be no trailing zeros.
ie
DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'FFFFFFFK");
Custom date and time format strings
You can achieve this fairly easily using Regex. Here's one way.
string result = Regex.Replace("2013-06-26T19:51:38.0083980Z", "0+Z$", "Z");
// result == "2013-06-26T19:51:38.008398Z"
string result2 = Regex.Replace("2013-06-26T19:51:38.0083988Z", "0+Z$", "Z")
// result2 == "2013-06-26T19:51:38.0083988Z"
I would write my own help method like;
public string GetDtString(DateTime dt)
{
RegEx rgx = new RegEx("[1-9]0+Z\b");
return rgx.Replace(dt.ToString("o"), System.String.Empty);
}
It basically just returns the dt string with all 0's which occur after a digit 1-9 and before Z\b (Z followed by a word boundary) with an empty string.

Adding comma between longer numbers [duplicate]

This question already has answers here:
.NET String.Format() to add commas in thousands place for a number
(23 answers)
Closed 9 years ago.
I'm trying to put comma's between long numbers automatically, but so far without success. I'm probably making a very simple mistake, but so far I can't figure it out. This is the code I currently have, but for some reason I'm getting 123456789 as the output.
string s = "123456789";
string.Format("{0:#,###0}", s);
MessageBox.Show(s); // Needs to output 123,456,789
var input = 123456789;
// these two lines amount to the same thing
Console.WriteLine(input.ToString("N0"));
Console.WriteLine(string.Format("{0:N0}", input));
If, as per your question, you need to start with a string:
var stringInput = "123456789";
var input = int.Parse(stringInput);
// these two lines amount to the same thing
Console.WriteLine(input.ToString("N0"));
Console.WriteLine(string.Format("{0:N0}", input));
You'll possibly also need to take culture into account when parsing/formatting. See the overloads that take an IFormatProvider.
Try this:
string value = string.Format("{0:#,###0}", 123456789);
In your code you are missing the initial { in the format string, and then number formatting options apply to numbers, while your s is a string.
You could convert the string to a number with int.Parse:
int s = int.Parse("123456789");
string value = string.Format("{0:#,###0}", 123456789);
MessageBox.Show(value);
This should work (you need to pass String.Format() a number, not another String):
Int32 i = 123456789;
String s = String.Format("{0:#,###0}", i);
MessageBox.Show(s);
But consider the format string you're using...there are cleaner options available, as others are suggesting.
Look at the number formatting information on MSDN: Standard Numeric Format Strings, or optionally at the custom format strings: Custom Numeric Format Strings.
For custom number formats:
The "," character serves as both a group separator and a number scaling specifier.
double value = 1234567890;
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));
// Displays 1,234,567,890
Console.WriteLine(value.ToString("#,##0,,", CultureInfo.InvariantCulture));
// Displays 1,235
There is so much wrong with your code, that's it's hard to describe every detail.
Look at this example:
namespace ConsoleApplication1
{
using System;
public class Program
{
public static void Main()
{
const int Number = 123456789;
var formatted = string.Format("{0:#,###0}", Number);
Console.WriteLine(formatted);
Console.ReadLine();
}
}
}

Categories