String.Format in C# - c#

I have an values like
1,000
25,000
500,000
Need to convert above values as like below without comma
1000
25000
500000
How to acheive this in C#?
how to get reverse output of this -
string.Format("{0:n}", 999999)

You can use the Replace function of the string class like so:
string str = "25,000";
str = str.Replace(",", "");
EDIT:
As suggested by Matthew Watson from the comments
If the string is returned from string.Format("{0:n}", 999999) run on a
machine in a locale that uses "." as the thousands separator, this
will fail
updated answer:
string num = "25,000";
NumberFormatInfo currentInfo = CultureInfo.CurrentCulture.NumberFormat;
num = num.Replace(currentInfo.NumberGroupSeparator, "");

Related

C# Convert back from thousand separator to int

I have a code that makes an int to a thousend separator but when I try to save this value in the text box to the database I want to remove the space between. I could not do this with replace(" ","").
YearTB.Text = (String.Format(culture, "{0:n0}", Int32.Parse(YearTB.Text)));
What is in the box is for example "536 396" but the space between is not an " ". its the effect of the thousand seperator. How can I return it back to int. "536396".
If you just want to convert to a string without the thousands rather than to an int:
string result = text.Replace(culture.NumberFormat.NumberGroupSeparator, "");
This assumes that culture is the CultureInfo with which the number was formatted using a thousand separator.
Alternatively if you want to convert to an int, you can use int.Parse() directly and specify that you want to allow the thousands separator (which I think is a better approach):
int result = int.Parse(text, NumberStyles.AllowThousands, culture);
Try this
string str = "536 396";
str = Regex.Replace(str, #"\s", "");

Add separator to string?

I got here an sample string output in numbers:
123456789
But What my goal is to make it like this:
Format: 123-45-6789
I was able to look for some codes here but they all have a fix interval , which is not fit from what I am making. It is required to make the input format to be like this "123-45-6789" but when saving it is only required 9 characters long because there is a limit to the space where it should be stored so I used this code to met the 9 characters long storation.
Input.Text = Input.Text.Trim().Replace("-", string.Empty);
Bio.SetString(UserName, "9Character", Input.Text.Trim());
But when displaying it again , it is again required to be on this format , 123-45-6789. Which is my problem.
You can also try something like:
string val = "123456789";
val = val.Substring(0, 3) + "-" + val.Substring(3, 2) + "-" + val.Substring(5) ;
Here is a working DEMO
something like,
string number = "123456789";
var output = Regex.Replace(number,
#"^(\d{3})[ -]?(\d{2})[ -]?(\d{4})( x\d+)?",
#"$1-$2-$3$4", RegexOptions.IgnorePatternWhitespace);
Console.WriteLine($"formated {output}");
output : formated 123-45-6789
Demo

Creating fixed length numeric string

I have a certain number of files for which I need the filenames in my program. The files have a fixed naming fashion i.e. (prefix + digits).jpg. For e.g.: head001.jpg, head002.jpg, head003.jpg etc. etc.
The number of digits, in the end, can be varying - so the program has variables to change where the file naming starts from, where it ends and how many number digits are used in the naming. For e.g: A second scenario could be - tail00001.jpg, tail00002.jpg, tail00003.jpg etc. until tail00100.jpg
And in this case: start digit would be 0, end digit would be 100 and numDigits would be 5
In C++, I’ve seen this formatting being done as follows:
format <<prefix<<"%0"<<numDigits<<"d."<<filetype; //where format is a stringstream
However, I’m not quite sure about the best way to do this in C# and would like to know how to solve this.
Just use string.Format, with a precision specifier saying how many digits you want:
string name = string.Format("tail{0:d6}.jpg", index);
See the MSDN documentation for standard numeric string formats for more details.
You can build the string format up programmatically of course:
string name = string.Format("tail{0:d" + digits + "}.jpg", index);
Or use PadLeft as suggested by Vano. You might still want to use string.Format though:
string name = string.Format("tail{0}.jpg",
index.ToString().PadLeft(digits, '0'));
Using PadLeft has the advantage that it's easier to change the padding value, although I would imagine you'd always want it to be 0 anyway.
string has PadLeft method:
int n1 = 1;
string t1 = n1.ToString().PadLeft(5, '0'); // This will return 00001
int n10 = 10;
string t2 = n10.ToString().PadLeft(5, '0'); // This will return 00010 and so on...
You can do this using string.Format
var result = string.Format("{0}{1:00000}{2}", prefix, number, filetype)
Or you could use padleft
var result = prefix + number.ToString().PadLeft('0', numDigits) + "." + extension;
Or you can use a mix of the two :)
..and in this case: start digit would be 0, end digit would be 100 and
numDigits would be 5
You could use String.Format and the decimal format/precision specifier "D"` and a for-loop:
int start = 0;
int end = 100;
int numDigits = 5;
string name = "tail";
string extension = ".jpg";
for(int i = start; i <= end; i++)
{
string fileName = string.Format(
"{0}{1}{2}", name, i.ToString("D" + numDigits), extension);
Console.WriteLine(fileName);
}
Outputs:
tail00000.jpg
tail00001.jpg
tail00002.jpg
tail00003.jpg
tail00004.jpg
tail00005.jpg
tail00006.jpg
tail00007.jpg
tail00008.jpg
tail00009.jpg
tail00010.jpg
....
tail100.jpg
For modern .NET 5.0+ (2021 update)
int myint = 100;
string zeroPadded = $"{myint:d8}"; // "00000100"
string spacePadded = $"{myint,8}"; // " 100"

How can I add a SPACE halfway through a string value?

I'm trying to create a STRING in JSON format. However, one of the fields (from my editing/removing ALL spaces) now leaves a line like "START":"13/08/1410:30:00". However, I want to add a space between the date and time? I have tried using the ToCharArray() method to split the string, but I am at a loss as to how to add a space between the DATE and TIME part of the string?
For Example, i am trying to get: "START":"13/08/14 10:30:00" but instead am getting
"START":"13/08/1410:30:00"
Please note. The length of the string before the space requirement will always be 17 characters long. I am using VS 2010 for NETMF (Fez Panda II)
If the split position is always 17, then simply:
string t = s.Substring(0, 17) + " " + s.Substring(17);
Obviously you will have to sort the numbers out, but thats the general idea.
String.Format("{0} {1}", dateString.Substring(0, 17), dateString.Substring(17, dateString.Length - 17);
Or you can use the StringBuilder class:
var finalString = new StringBuilder();
for (var i = 0; i < dateString.Length; i++){
if (i == 17)
finalString.Add(" ");
else
finalString.Add(dateString.ToCharArray()[i]);
}
return finalString.ToString();
If the date time format always the same you can use string.Insert method
var output = #"""START"":""13/08/1410:30:00""".Insert(17, " ");
Strings in .Net are immutable: you can never change them. However, you can easily create a new string.
var date_time = dateString + " " + timeString;

Remove formatting from a string: "(123) 456-7890" => "1234567890"?

I have a string when a telephone number is inputted - there is a mask so it always looks like "(123) 456-7890" - I'd like to take the formatting out before saving it to the DB.
How can I do that?
One possibility using linq is:
string justDigits = new string(s.Where(c => char.IsDigit(c)).ToArray());
Adding the cleaner/shorter version thanks to craigmoliver
string justDigits = new string(s.Where(char.IsDigit).ToArray())
You can use a regular expression to remove all non-digit characters:
string phoneNumber = "(123) 456-7890";
phoneNumber = Regex.Replace(phoneNumber, #"[^\d]", "");
Then further on - depending on your requirements - you can either store the number as a string or as an integer. To convert the number to an integer type you will have the following options:
// throws if phoneNumber is null or cannot be parsed
long number = Int64.Parse(phoneNumber, NumberStyles.Integer, CultureInfo.InvariantCulture);
// same as Int64.Parse, but returns 0 if phoneNumber is null
number = Convert.ToInt64(phoneNumber);
// does not throw, but returns true on success
if (Int64.TryParse(phoneNumber, NumberStyles.Integer,
CultureInfo.InvariantCulture, out number))
{
// parse was successful
}
Since nobody did a for loop.
long GetPhoneNumber(string PhoneNumberText)
{
// Returns 0 on error
StringBuilder TempPhoneNumber = new StringBuilder(PhoneNumberText.Length);
for (int i=0;i<PhoneNumberText.Length;i++)
{
if (!char.IsDigit(PhoneNumberText[i]))
continue;
TempPhoneNumber.Append(PhoneNumberText[i]);
}
PhoneNumberText = TempPhoneNumber.ToString();
if (PhoneNumberText.Length == 0)
return 0;// No point trying to parse nothing
long PhoneNumber = 0;
if(!long.TryParse(PhoneNumberText,out PhoneNumber))
return 0; // Failed to parse string
return PhoneNumber;
}
used like this:
long phoneNumber = GetPhoneNumber("(123) 456-7890");
Update
As pr commented many countries do have zero's in the begining of the number, if you need to support that, then you have to return a string not a long. To change my code to do that do the following:
1) Change function return type from long to string.
2) Make the function return null instead of 0 on error
3) On successfull parse make it return PhoneNumberText
You can make it work for that number with the addition of a simple regex replacement, but I'd look out for higher initial digits. For example, (876) 543-2019 will overflow an integer variable.
string digits = Regex.Replace(formatted, #"\D", String.Empty, RegexOptions.Compiled);
Aside from all of the other correct answers, storing phone numbers as integers or otherwise stripping out formatting might be a bad idea.
Here are a couple considerations:
Users may provide international phone numbers that don't fit your expectations. See these examples So the usual groupings for standard US numbers wouldn't fit.
Users may NEED to provide an extension, eg (555) 555-5555 ext#343 The # key is actually on the dialer/phone, but can't be encoded in an integer. Users may also need to supply the * key.
Some devices allow you to insert pauses (usually with the character P), which may be necessary for extensions or menu systems, or dialing into certain phone systems (eg, overseas). These also can't be encoded as integers.
[EDIT]
It might be a good idea to store both an integer version and a string version in the database. Also, when storing strings, you could reduce all punctuation to whitespace using one of the methods noted above. A regular expression for this might be:
// (222) 222-2222 ext# 333 -> 222 222 2222 # 333
phoneString = Regex.Replace(phoneString, #"[^\d#*P]", " ");
// (222) 222-2222 ext# 333 -> 2222222222333 (information lost)
phoneNumber = Regex.Replace(phoneString, #"[^\d]", "");
// you could try to avoid losing "ext" strings as in (222) 222-2222 ext.333 thus:
phoneString = Regex.Replace(phoneString, #"ex\w+", "#");
phoneString = Regex.Replace(phoneString, #"[^\d#*P]", " ");
Try this:
string s = "(123) 456-7890";
UInt64 i = UInt64.Parse(
s.Replace("(","")
.Replace(")","")
.Replace(" ","")
.Replace("-",""));
You should be safe with this since the input is masked.
You could use a regular expression or you could loop over each character and use char.IsNumber function.
You would be better off using regular expressions. An int by definition is just a number, but you desire the formatting characters to make it a phone number, which is a string.
There are numerous posts about phone number validation, see A comprehensive regex for phone number validation for starters.
As many answers already mention, you need to strip out the non-digit characters first before trying to parse the number. You can do this using a regular expression.
Regex.Replace("(123) 456-7890", #"\D", String.Empty) // "1234567890"
However, note that the largest positive value int can hold is 2,147,483,647 so any number with an area code greater than 214 would cause an overflow. You're better off using long in this situation.
Leading zeros won't be a problem for North American numbers, as area codes cannot start with a zero or a one.
Alternative using Linq:
string phoneNumber = "(403) 259-7898";
var phoneStr = new string(phoneNumber.Where(i=> i >= 48 && i <= 57).ToArray());
This is basically a special case of C#: Removing common invalid characters from a string: improve this algorithm. Where your formatng incl. White space are treated as "bad characters"
'you can use module / inside sub main form VB.net
Public Function ClearFormat(ByVal Strinput As String) As String
Dim hasil As String
Dim Hrf As Char
For i = 0 To Strinput.Length - 1
Hrf = Strinput.Substring(i, 1)
If IsNumeric(Hrf) Then
hasil &= Hrf
End If
Next
Return Strinput
End Function
'you can call this function like this
' Phone= ClearFormat(Phone)
public static string DigitsOnly(this string phoneNumber)
{
return new string(
new[]
{
// phoneNumber[0], (
phoneNumber[1], // 6
phoneNumber[2], // 1
phoneNumber[3], // 7
// phoneNumber[4], )
// phoneNumber[5],
phoneNumber[6], // 8
phoneNumber[7], // 6
phoneNumber[8], // 7
// phoneNumber[9], -
phoneNumber[10], // 5
phoneNumber[11], // 3
phoneNumber[12], // 0
phoneNumber[13] // 9
});
}

Categories

Resources