Is there a way to tell the String.Format() function (without writing my own function) how many placeholders there are dynamically? It we be great to say 15, and know I'd have {0}-{14} generated for me. I'm generate text files and I often have more than 25 columns. It would greatly help.
OK,
I will rephrase my question. I wanted to know if it is at all possible to tell the String.Format function at execution time how many place-holders I want in my format string without typing them all out by hand.
I'm guessing by the responses so far, I will just go ahead and write my own method.
Thanks!
You could use Enumerable.Range and LINQ to generate your message string.
Enumerable.Range(0, 7).Select(i => "{" + i + "}").ToArray()
generates following string:
"{0}{1}{2}{3}{4}{5}{6}"
Adding a bit to AlbertEin's response, I don't believe String.Format can do this for you out-of-the-box. You'll need to dynamically create the format string prior to using the String.Format method, as in:
var builder = new StringBuilder();
for(var i = 0; i < n; ++i)
{
builder.AppendFormat("{0}", "{" + i + "}");
}
String.Format(builder.ToString(), ...);
This isn't exactly readable, though.
Why use string.Format when there is no formatting (atleast from what I can see in your question)? You could use simple concatenation using stringbuilder instead.
There is a way to do this directly:
Just create a custom IFormatProvider, then use this overload of string.Format.
For example, if you want to always have 12 decimal points, you can do:
CultureInfo culture = Thread.CurrentThread.CurrentCulture.Clone(); // Copy your current culture
NumberFormatInfo nfi = culture.NumberFormat;
nfi.NumberDecimalDigits = 12; // Set to 12 decimal points
string newResult = string.Format(culture, "{0}", myDouble); // Will put it in with 12 decimal points
Related
I have an issue where I need to add two numeric strings "$1,234.56" and "$9,876.54" and get a string "$11,111.10"
I can convert the strings to numbers, perform the addition, but I don't know of a good way to preserve the formatting when I ToString() the result. I can add a couple of if statements along the lines: does the input have dollar sign, decimal point, percent sign and construct the format string accordingly, but this is clunky and will fail if we ever need to support more than one number format.
Does anyone know how to add numeric strings and preserve formatting?
EDIT: To answer the questions. The format of all strings being added at a given time is the same ie: I don't need to worry about adding $ and £ (in fact £ is not currently supported), However, there are several possible formats that are currently supported and more may be added in the future:
$1,234.00; $1,234; 1234; 1,234; 1,234.00; 1234%; 1,234%; 1,234.00%
I would suggest using the first numeric string as a template and create a number format from it:
var posshalves = firstNumericString.Split('.');
var fmthalves = new string[2] { posshalves[0], (posshalves.Length < 2 ? "" : "."+posshalves[1])};
var intfmt = Regex.Replace(fmthalves[0], #"[0-9]", "#");
intfmt = Regex.Replace(intfmt, #"#+", "#");
var decfmt = Regex.Replace(fmthalves[1], "[0-9]", "0");
var format = $"{intfmt}{decfmt}";
Hi all I want to know something regarding to fixed-string in regular expression.
How to represent a fixed-string, regardless of special characters or alphanumeric in C#?
For eg; have a look at the following string:
infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X
The entire string before X will be fixed-string (ie; the whole sentence will appear the same) BUT only X will be the decimal variable.
What I want is that I want to append decimal number X to the fixed string. How to express that in terms of C# regular expression.
Appreciate your help
string fulltext = "inifinity.world.uk/Members/namelist.aspx?ID=-1&fid=" + 10;
if you need to modify existing url, dont use regex, string.Format or string.Replace you get problem with encoding of arguments
Use Uri and HttpUtility instead:
var url = new Uri("http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=X");
var query = HttpUtility.ParseQueryString(url.Query);
query["fid"] = 10.ToString();
var newUrl = url.GetLeftPart(UriPartial.Path) + "?" + query;
result: http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=10
for example, using query["fid"] = "%".ToString(); you correctly generate http://infinity.world.uk/Members/namelist.aspx?ID=-1&fid=%25
demo: https://dotnetfiddle.net/zZ9Y1h
String.Format is one way of replacing token values in a string, if that's what you want. In the example below, the {0} is a token, and String.Format takes the fixedString and replaces the token with the value of myDecimal.
string fixedString = "infinity.world.uk/Members/namelist.aspx?ID=-1&fid={0}";
decimal myDecimal = 1.5d;
string myResultString = string.Format(fixedString, myDecimal.ToString());
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();
}
}
}
I am getting the following values from database:
99, 12, 12.2222, 54.98, 56, 17.556
Now I want to show that values like below:
99%, 12%, 12.22% , 54.98% , 56%, 17.55%
Please give me any suggestion to acchive this.
Its very easy in C#:
[EDIT]
var val = 99.569;
string result = string.Format("{0:0.##}%", val);
You can take a look for Format method of string class:
http://msdn.microsoft.com/en-us/library/fht0f5be.aspx
and I recomend you to take a look on custom format strings:
http://msdn.microsoft.com/en-us/library/0c899ak8.aspx
Use the ToString method that takes a string format - the format you want is "P2" or the custom format #0.##%. Both of these formatting options multiply by 100, expecting your data to be in standard percent format so you will need to divide to accomadate and use it.
To use ToString without the divide you can use "#0.##\%" which will format the numeric part and include the percent sign as a literl, this is the equivilent for ToString as the format from Anton Semenov's answer using the string.Format function on this thread.
Msdn article - Standard Formats
Msdn article - Custom Formats
to formart 12.2222 use f
string.Format("{0:f}%", 12.2222); //output 12,22%
Try this Out
List<double> myList = new List<double>();
myList.Add(0.1234);
myList.Add(99);
myList.Add(12.1234);
myList.Add(54.98);
foreach (double d in myList)
{
string First = string.Format("{0:0.00%}", d); //Multiply value by 100
Console.WriteLine(First);
string Second = string.Format("{0:P}", d);//Multiply value by 100
Console.WriteLine(Second);
string Third = string.Format("{0:P}%", d.ToString());//Use this One
Console.WriteLine(Third);
string Four = d.ToString() + "%"; //Not a good idea but works
Console.WriteLine(Four);
Console.WriteLine("=====================");
}
Console.ReadLine();
I have made a little trick here {0:P} will multiply your given value by 100 and then show it but you just want to place a % sign after value so first convert the given value to TOString than apply {0:p}
If you want to specify the number of decimal places to 2 (ie. not 12.2222%, but 12.22%), then use:
val.ToString("0.00") + "%"
Note that this will round the number off, so 12.226 would be shown as 12.23%, etc.
Before using String.Format to format a string in C#, I would like to know how many parameters does that string accept?
For eg. if the string was "{0} is not the same as {1}", I would like to know that this string accepts two parameters
For eg. if the string was "{0} is not the same as {1} and {2}", the string accepts 3 parameters
How can I find this efficiently?
String.Format receives a string argument with format value, and an params object[] array, which can deal with an arbitrary large value items.
For every object value, it's .ToString() method will be called to resolve that format pattern
EDIT: Seems I misread your question. If you want to know how many arguments are required to your format, you can discover that by using a regular expression:
string pattern = "{0} {1:00} {{2}}, Failure: {0}{{{1}}}, Failure: {0} ({0})";
int count = Regex.Matches(Regex.Replace(pattern,
#"(\{{2}|\}{2})", ""), // removes escaped curly brackets
#"\{\d+(?:\:?[^}]*)\}").Count; // returns 6
As Benjamin noted in comments, maybe you do need to know number of different references. If you don't using Linq, here you go:
int count = Regex.Matches(Regex.Replace(pattern,
#"(\{{2}|\}{2})", ""), // removes escaped curly brackets
#"\{(\d+)(?:\:?[^}]*)\}").OfType<Match>()
.SelectMany(match => match.Groups.OfType<Group>().Skip(1))
.Select(index => Int32.Parse(index.Value))
.Max() + 1; // returns 2
This also address #280Z28 last problem spotted.
Edit by 280Z28: This will not validate the input, but for any valid input will give the correct answer:
int count2 =
Regex.Matches(
pattern.Replace("{{", string.Empty),
#"\{(\d+)")
.OfType<Match>()
.Select(match => int.Parse(match.Groups[1].Value))
.Union(Enumerable.Repeat(-1, 1))
.Max() + 1;
You'll have to parse through the string and find the highest integer value between the {}'s...then add one.
...or count the number of sets of {}'s.
Either way, it's ugly. I'd be interested to know why you need to be able to figure out this number programatically.
EDIT
As 280Z28 mentioned, you'll have to account for the various idiosyncrasies of what can be included between the {}'s (multiple {}'s, formatting strings, etc.).
I rely on ReSharper to analyze that for me, and it is a pity that Visual Studio does not ship with such a neat feature.