Converting int to string with a specific format - c#

I'm trying to convert an classical integer value like:
2000
into a format like this:
2.000,00
I have tried the following methods:
String.valueOf(input.format());
And this method:
private String getCents(Decimal x){
String y = String.valueOf(x);
String z = '.';
if(y.contains(',')) z = ',';
y = y.substring(0, y.indexOf(z));
if(x - Decimal.valueOf(y) == 0)
return String.valueOf(x.format()) + z + '00';
else return String.valueOf(x.format());
}
But the string class doesn't contains the valueOf method for some reason. Is there any other way to do this ?

The class String does not contain the method valueOf, because this ain't Java, you know.
The method you are searching for is ToString, which allows a format-provider as an argument. The simplest way is another string which defines the format.
int i = 2000;
Console.WriteLine(i.ToString("#,##0.00"));
Console.ReadLine();
This will do what you want to do.
Read more about format-providers in the docs of the ToStringmethod.

given en-US culture
this will do:
string.Format(CultureInfo.GetCultureInfo("en-US"), "{0:N}", 2000)

Related

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"

Insert spaces into string using string.format

I've been using C# String.Format for formatting numbers before like this (in this example I simply want to insert a space):
String.Format("{0:### ###}", 123456);
output:
"123 456"
In this particular case, the number is a string. My first thought was to simply parse it to a number, but it makes no sense in the context, and there must be a prettier way.
Following does not work, as ## looks for numbers
String.Format("{0:### ###}", "123456");
output:
"123456"
What is the string equivalent to # when formatting? The awesomeness of String.Format is still fairly new to me.
You have to parse the string to a number first.
int number = int.Parse("123456");
String.Format("{0:### ###}", number);
of course you could also use string methods but that's not as reliable and less safe:
string strNumber = "123456";
String.Format("{0} {1}", strNumber.Remove(3), strNumber.Substring(3));
As Heinzi pointed out, you can not have format specifier for string arguments.
So, instead of String.Format, you may use following:
string myNum="123456";
myNum=myNum.Insert(3," ");
Not very beautiful, and the extra work might outweigh the gains, but if the input is a string on that format, you could do:
var str = "123456";
var result = String.Format("{0} {1}", str.Substring(0,3), str.Substring(3));
string is not a IFormattable
Console.WriteLine("123456" is IFormattable); // False
Console.WriteLine(21321 is IFormattable); // True
No point to supply a format if the argument is not IFormattable only way is to convert your string to int or long
We're doing string manipulation, so we could always use a regex.
Adapted slightly from here:
class MyClass
{
static void Main(string[] args)
{
string sInput, sRegex;
// The string to search.
sInput = "123456789";
// The regular expression.
sRegex = "[0-9][0-9][0-9]";
Regex r = new Regex(sRegex);
MyClass c = new MyClass();
// Assign the replace method to the MatchEvaluator delegate.
MatchEvaluator myEvaluator = new MatchEvaluator(c.ReplaceNums);
// Replace matched characters using the delegate method.
sInput = r.Replace(sInput, myEvaluator);
// Write out the modified string.
Console.WriteLine(sInput);
}
public string ReplaceNums(Match m)
// Replace each Regex match with match + " "
{
return m.ToString()+" ";
}
}
How's that?
It's been ages since I used C# and I can't test, but this may work as a one-liner which may be "neater" if you only need it once:
sInput = Regex("[0-9][0-9][0-9]").Replace(sInput,MatchEvaluator(Match m => m.ToString()+" "));
There is no way to do what you want unless you parse the string first.
Based on your comments, you only really need a simple formatting so you are better off just implementing a small helper method and thats it. (IMHO it's not really a good idea to parse the string if it isn't logically a number; you can't really be sure that in the future the input string might not be a number at all.
I'd go for something similar to:
public static string Group(this string s, int groupSize = 3, char groupSeparator = ' ')
{
var formattedIdentifierBuilder = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
if (i != 0 && (s.Length - i) % groupSize == 0)
{
formattedIdentifierBuilder.Append(groupSeparator);
}
formattedIdentifierBuilder.Append(s[i]);
}
return formattedIdentifierBuilder.ToString();
}
EDIT: Generalized to generic grouping size and group separator.
The problem is that # is a Digit placeholder and it is specific to numeric formatting only. Hence, you can't use this on strings.
Either parse the string to a numeric, so the formatting rules apply, or use other methods to split the string in two.
string.Format("{0:### ###}", int.Parse("123456"));

Converting [string].ToString([custom format])

How can I achieve formatting string to custom format:
int value = 5000;
String.Format("{0:## ###}", value);
value.ToString("##");
but with value as string, without using conversion to number?
something like this:
String.Format("{0:## ###}, "5000");
** UPDATE:
I'm trying to create a generic function:
public string FormatString(string value, string format = "") {
if (value == null){
return "";
}
return String.Format("{0:" + format + "}", value);
}
public bool OtherFunction(id){
var data = dc.GetData(id);
ViewBag.DescriptionText = FormatString(data.Description).Replace("\n", "<br />");
ViewBag.Phone = FormatString(data.Phone, "(##) ####-#####");
ViewBag.City= FormatString(data.City);
[...]
}
I don't think something like this exists. Like Jon said, this was design for numbers.
If you want just "format" with # you could write simple function, something like this
public string FormatString(string value, string format = "")
{
if (String.IsNullOrEmpty(value) || String.IsNullOrEmpty(format))
return value;
var newValue = new StringBuilder(format);
for (int i = 0; i < newValue.Length; i++)
{
if (newValue[i] == '#')
if (value.Length > 0)
{
newValue[i] = value[0];
value = value.Substring(1);
}
else
{
newValue[i] = '0';
}
}
return newValue.ToString();
}
Of course this is very simple one. You will have to check and decide what to do if format is too long (like here: fill with '0') and when he format is too short (here: just 'truncate' rest of value).
But I think you have an idea how to do this.
Somewhere on my disk I have code for something like this: formatting number in special ways/pattern for invoice number. If I will find this, I'll make some post on blog and paste the link
"5000" is a string. The only overload available for string.ToString() is the one with an IFormatProvider [1]. While you could actually implement that, you'll probably end up in something similar to int.Parse() which you don't like.
[1] http://msdn.microsoft.com/de-de/library/29dxe1x2(v=vs.110).aspx

How to split a string based on every third character regardless of what the character is in c# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
.NET String.Format() to add commas in thousands place for a number
I am trying to add commas to a number for the presentation layer and need to cast and then split the number on every third character in order to join on a ','.
So if i have a string like this
546546555
desired output:
546,546,555
Other times, the number could be longer or shorter:
254654
desired output:
254,654
Is it possible to split in this manner then join with a comma?
tahnks!
EDIT:
Hi Everyone,
Thanks very much for your help.
To add to this post I also found a way to do this in SQL:
SUBSTRING(CONVERT(varchar, CAST(NumItems AS money), 1), 0, LEN(CONVERT(varchar, CAST(NumDocs AS money), 1)) - 2) as [NumDocs]
Rather than splitting the string manually, you should convert it to a number (or leave it as a number), and call the ToString method with the appropriate formatting:
Example
int value = 546546555;
string displayValue = value.ToString("#,#");
See this MSDN page for different format values:
C - Currency format
D - Decimal format
E - Scientific format
F - Fixed point format
G - General format
N - Number format
P - Percent format
R - Round trip format
X - Hexadecimal format
You should do this by converting your string to an integer, using Parse or ideally TryParse and use string formatting to display it:
var str = "546546555";
var formatted = String.Empty;
int value = 0;
if(int.TryParse(str,out value))
{
formatted = value.ToString("#,#");
}
Live example: http://rextester.com/FHO11833
Assuming you aren't only trying to output numbers, here's a quick function that I believe would do what you are after:
string splitter(string tosplit, int num, string splitstring)
{
string output = "";
for (int i = 0; i < tosplit.Length; i += num)
if (i + num < tosplit.Length)
output += tosplit.Substring(i, num) + ",";
else
output += tosplit.Substring(i);
return output;
}
Here, the output of splitter("546546555", 3, ",") would be 546,546,555
This would not be ideal for numbers though, as the other answers would cover this case perfectly.
Not very good code, but it works.
public static string GetString(string val, int number)
{
List<string> res = new List<string>();
res.Add("");
int counter = 0, i = 0;
while (i < val.Length)
{
while (res[counter].Length < number && i < val.Length)
{
res[counter] += val[i];
i++;
}
res.Add("");
counter++;
}
return string.Join(",", res.Where(r => !string.IsNullOrEmpty(r)));
}
val - your input string
number - number of characters you want to split, equals to 3 in your case
Gene S and Dan seem to have the answer IMHO. The nice thing about using the built in formatting is that you can write localizable code. For example, the "," is the numeric group separator in the US, but the "." is used in Spain.
var val = 12345678;
CultureInfo c = CultureInfo.CurrentCulture;
Application.CurrentCulture = new CultureInfo("EN-us");
var s = String.Format("{0:#,#}", val);
Application.CurrentCulture = new CultureInfo("ES-es");
var i = String.Format("{0:#,#}", val);
Application.CurrentCulture = c;

C# 2.0 function which will return the formatted string

I am using C# 2.0 and I have got below type of strings:
string id = "tcm:481-191820"; or "tcm:481-191820-32"; or "tcm:481-191820-8"; or "tcm:481-191820-128";
The last part of string doesn't matter i.e. (-32,-8,-128), whatever the string is it will render below result.
Now, I need to write one function which will take above string as input. something like below and will output as "tcm:0-481-1"
public static string GetPublicationID(string id)
{
//this function will return as below output
return "tcm:0-481-1"
}
Please suggest!!
If final "-1" is static you could use:
public static string GetPublicationID(string id)
{
int a = 1 + id.IndexOf(':');
string first = id.Substring(0, a);
string second = id.Substring(a, id.IndexOf('-') - a);
return String.Format("{0}0-{1}-1", first, second);
}
or if "-1" is first part of next token, try this
public static string GetPublicationID(string id)
{
int a = 1 + id.IndexOf(':');
string first = id.Substring(0, a);
string second = id.Substring(a, id.IndexOf('-') - a + 2);
return String.Format("{0}0-{1}", first, second);
}
This syntax works even for different length patterns, assuming that your string is
first_part:second_part-anything_else
All you need is:
string.Format("{0}0-{1}", id.Substring(0,4), id.Substring(4,5));
This just uses substring to get the first four characters and then the next five and put them into the format with the 0- in there.
This does assume that your format is a fixed number of characters in each position (which it is in your example). If the string might be abcd:4812... then you will have to modify it slightly to pick up the right length of strings. See Marco's answer for that technique. I'd advise using his if you need the variable length and mine if the lengths stay the same.
Also as an additional note your original function of returning a static string does work for all of those examples you provided. I have assumed there are other numbers visible but if it is only the suffix that changes then you could happily use a static string (at which point declaring a constant or something rather than using a method would probably work better).
Obligatory Regular Expression Answer:
using System.Text.RegularExpressions;
public static string GetPublicationID(string id)
{
Match m = RegEx.Match(#"tcm:([\d]+-[\d]{1})", id);
if(m.Success)
return string.Format("tcm:0-{0}", m.Groups[1].Captures[0].Value.ToString());
else
return string.Empty;
}
Regex regxMatch = new Regex("(?<prefix>tcm:)(?<id>\\d+-\\d)(?<suffix>.)*",RegexOptions.Singleline|RegexOptions.Compiled);
string regxReplace = "${prefix}0-${id}";
string GetPublicationID(string input) {
return regxMatch.Replace(input, regxReplace);
}
string test = "tcm:481-191820-128";
stirng result = GetPublicationID(test);
//result: tcm:0-481-1

Categories

Resources