What is the meaning of {0}\{1} in c#, it returns some string, but in which format and what kind of string?
It means that it is expecting parameters to be replaced in string. something like.
string.Format("{0}{1}","parameter1","parameter2");
You may see: Composite Formatting
A composite format string and object list are used as arguments of
methods that support the composite formatting feature. A composite
format string consists of zero or more runs of fixed text intermixed
with one or more format items. The fixed text is any string that you
choose, and each format item corresponds to an object or boxed
structure in the list. The composite formatting feature returns a new
result string where each format item is replaced by the string
representation of the corresponding object in the list.
These are the arguments/params usually used in the string format function:
DateTime dat = new DateTime(2012, 1, 17, 9, 30, 0);
string city = "Chicago";
int temp = -16;
string output = String.Format("At {0} in {1}, the temperature was {2} degrees.",
dat, city, temp);
Console.WriteLine(output);
// The example displays the following output:
// At 1/17/2012 9:30:00 AM in Chicago, the temperature was -16 degrees.
See the documentation
They are format specifier, used with string.Format or StringBuilder.AppendFormat and similar functions.
See the manual for string.Format for a detailed explanation.
Related
I know this question has been answered many times before however, I'm convinced the code I have is correct but isn't working correctly.
string total = ds.Tables[0].Rows[0][0].ToString();
string test = string.Format("{0:N}", total);
lbl_totalValue.Text = test;
This code isn't adding the commas into my value like it desire it to.
Can anyone see why?
When you put
string total = ds.Tables[0].Rows[0][0].ToString();
it means implicit G ("General") format string
string total = ds.Tables[0].Rows[0][0].ToString("G");
Do not format prematurely:
var total = ds.Tables[0].Rows[0][0]; // Value from table
string test = string.Format("{0:N}", total); // Format total with "N" format string
Your code is trying to format a string. If the DataTable contains a number you can pass the format specifier to ToString(), eg
var test=ds.Tables[0].Rows[0][0].ToString("N");
Or store the contents in a local variable and use String.Format :
var total = ds.Tables[0].Rows[0][0];
string test = string.Format("{0:N}", total);
If the datatable contains a string though, you'd have to parse it to a numeric type first
You have to use the string.Format with a number type, instead of string. In this case, the variable total is a string, it must be a number.
There are 8 overloads for the Strig.Format method. You are using this specific one: Format(String, Object) in which you pass a String value as argument of the second parameter. This is because you are using a string variable (total) to assign the value from the dataset in:
string total = ds.Tables[0].Rows[0][0].ToString();
Besides you are using .ToString() to retrieve it as a String.
If you are using SQL Server as data source to your ds dataset and you are certain about the SQL data type then you can assign that value directly to a variable with the corresponding C# type. To put it in a different way, SQL data types are mapped to C# data types.
If you are not sure about the C# data type of ds.Tables[0].Rows[0][0] then you could simply do the following:
Object total = ds.Tables[0].Rows[0][0];
string test = string.Format("{0:N}", total);
lbl_totalValue.Text = test;
And this way you literally use the Format(String, Object) overload of String.Format.
Say you have a string 5/9/2010 and you want to rearrange it to read 2010/5/9. How would you go about doing that?
I want to sort a list by a string that happens to be a date. While I could make it into a date, I want to stick with a string, if possible because the time part of the datetime is hard to eliminate. (This is being used in an sqlite database for a Unity3d App.)
Forgive me if this is a duplicate.
If you can guarantee that the string will always be the same input format, you can split the string on the /:
string input = "5/9/2010";
string[] inputSections = input.Split('/');
string output = string.Format("{0}/{1}/{2}", inputSections[2], inputSections[0], inputSections[1]);
Working Fiddle
My code is very verbose, you can certainly simplify it for your needs. I would also utilize the string inerpolation feature of C# 6 if it is available to you:
string input = "5/9/2010";
string[] inputSections = input.Split('/');
string output = $"{inputSections[2]}/{inputSections[1]}/{inputSections[0]}";
I would recommend parsing the date, in the off chances that the input date is not exactly in the format you were expecting, but was indeed a valid date. This is the situations parsing is for.
CultureInfo us = CultureInfo.GetCultureInfo("en-US");
string input = "5/9/2010";
DateTime date = DateTime.Parse(input, us);
Console.WriteLine(date.ToString("yyyy/MM/dd", us));
You can test here
I have a date range come like this,
string ActualReleaseDates ="7/8/2016, 7/9/2016, 7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate ="07/11/2016";
I want to check NewsReleaseDate is inside the ActualReleaseDates
But in the following code it return as a false.
if (ActualReleaseDates.Split(',').Contains(NewsReleasedDate.TrimStart(new Char[] { '0' })))
{
//some code here
}
The immediate problem is that after splitting your ActualReleaseDates string, there isn't an entry of "7/11/2016"... instead, there's an entry of " 7/11/2016"... note the space.
But more fundamentally, just trimming the start of NewsReleasedDate won't help if the value is something like "07/08/2016"... what you should be doing is handling these values as dates, rather than as strings:
Split ActualReleaseDates by comma, then parse each value (after trimming whitespace) in an appropriate format (which I suspect is M/d/yyyy) so that you get a List<DateTime>.
Parse NewsReleasedDate in the appropriate format, which I suspect is MM/dd/yyyy, so you get a DateTime.
See whether the parsed value from the second step occurs in the list from the first step.
(I'd personally recommend using Noda Time and parsing to LocalDate values, but I'm biased...)
Fundamentally, you're trying to see whether one date occurs in a list of dates... so make sure you get your data into its most appropriate representation as early as possible. Ideally, avoid using strings for this at all... we don't know where your data has come from, but if it started off in another representation and was converted into text, see if you can avoid that conversion.
The white space problem. You can use trim() and ' 7/11/2016' will be '7/11/2016'
var ActualReleaseDates = "7/8/2016, 7/9/2016, 7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
var NewsReleasedDate = "07/11/2016";
var splitActualReleaseDates = ActualReleaseDates.Split(',').Select(x => x.Trim());
if (splitActualReleaseDates.Contains(NewsReleasedDate.TrimStart(new Char[] { '0' })))
{
}
You can use linq to convert your strings into DateTime objects and compare them instead of strings
string ActualReleaseDates ="7/8/2016,7/9/2016,7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate ="07/11/2016";
var releaseDates = ActualReleaseDates.Split(',').Select(x => DateTime.Parse(x));
var newsReleased = DateTime.Parse(NewsReleaseDate);
if (releaseDates.Contains(newsReleased))
{
//some code here
}
please note that DateTime is parsed respectively to the current Culture. You can use DateTime.ParseExact if you want to specify exact date format.
You can Prase to DateTime before doing the query like this:
(I think this is the most accurate and guaranteed way to compare dates)
Func<string, DateTime> stringToDate = s => DateTime.ParseExact(s.Trim(), "M/d/yyyy",
CultureInfo.InvariantCulture);
DateTime newReleaseDateTime = stringToDate(NewsReleasedDate);
bool result = ActualReleaseDates.Split(',').Select(x => stringToDate(x))
.Contains(newReleaseDateTime);
It returns false because of the date 07/11/2016 stored in NewsReleasedDate is stored as string with a '0' at the begining. And in the ActualReleaseDates string you have white spaces between the ',' and numbers.
Try to rewrite theese strings like this :
ActualReleaseDates ="7/8/2016,7/9/2016,7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016"; // white spaces removed.
and the variable like this :
NewsReleasedDate ="7/11/2016"; // 0 removed
This is my code example :
string ActualReleaseDates = "7/8/2016,7/9/2016,7/11/2016,7/3/2016,7/10/2016,7/17/2016,7/24/2016,7/31/2016";
string NewsReleasedDate = "7/11/2016";
string[] dates = ActualReleaseDates.Split(',');
Console.WriteLine(dates.Contains(NewsReleasedDate));
This is not the best way to compare dates, you can use Date class which is usefull to do this kind of comparations.
I have a variable of type Long i.e.
long quantity=1000;
I want to display it like 1,000 in Grid (Must need commas)
How do i achieve this?
I am using a Telerik Grid and I am binding the data as follows:
columns.Bound(tempProductList => tempProductList.tempProductListQuantity) .Title("Quantity")
Here you have a list of all the standard numeric formats. I think "N" is the one you want.
long l = 1234;
string s = l.ToString("N0"); //gives "1,234"
The "0" after the format specifier is the number of desired decimal places (usually 2 by default).
Note that this version is culture-sensitive, i.e., in my country, we use dots (".") as thousand separators, so the actual returned value will be "1.234" instead of the "1,234". If this is desired behaviour, just leave it as is, but if you need to use commas always, then you should specify a culture as a parameter to the ToString method, like
l.ToString("N0", CultureInfo.InvariantCulture); //always return "1,234"
You could create a Custom Culture that will allow you to specify the thousand separator.
From this article:
//Create first the format provider the String.Format
//will use to format our string
CultureInfo cultureToUse = new CultureInfo("fi-FI");
Console.WriteLine("Using the following CultureInfor " +
cultureToUse.Name);
//Now practice some decimal numbers
//Here we override the culture specific formattings
cultureToUse.NumberFormat.CurrencyDecimalDigits = 3;
cultureToUse.NumberFormat.NumberDecimalDigits = 3;
cultureToUse.NumberFormat.NumberGroupSeparator = " ";
cultureToUse.NumberFormat.CurrencySymbol = "euro";
cultureToUse.NumberFormat.NumberDecimalSeparator = ",";
Next you would need to use this culture when formatting the numbers.
You could do the formattin gby hand but you could also assign the culture to the Current(UI)Culture property of the current thread.
If you want to consider the international point of view, there will not be always commas before the decimal part. ToString function will give you what you want.
(1000.0).ToString("N",new CultureInfo("en-US")) = 1,000.00
(1000.0).ToString("N",new CultureInfo("is-IS")) = 1.000,00
using Silverlight I am having trouble with the following code:
CultureInfo culture = new CultureInfo("ar-EG");
CultureInfo invCulture = CultureInfo.InvariantCulture;
Result.Text = String.Format(culture.NumberFormat, "{0:C}", 70000000.00);
// Does Not Work
//Result2.Text = String.Format(invCulture.NumberFormat, "{0}", double.Parse(Result.Text, invCulture));
// Does Not Work
//Result2.Text = String.Format(culture.NumberFormat, "{0}", double.Parse(Result.Text, culture.NumberFormat));
// Does Not Work
//Result2.Text = Convert.ToString(Decimal.Parse(Result.Text.Replace(" ", ""), NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowTrailingWhite));
Ultimately I'd like prove that I can transform a number to the Egyptian (Arabic) currency formatted string and then get my original number again.
Any time I try to convert my number back to the original double or decimal I receive an FormatException error 'Input string was not in a correct format.'.
Any help please?
You won't be able to convert the output string back to a number using double.Parse as that expects the input to be purely numeric.
If you want the value to go backwards and forwards from a number to a formatted string put the formatting in the XAML:
<TextBlock Text={Binding NumericValue, StringFormat=c, Mode=TwoWay} />
Source
Given that you're not in XAML you'll need to strip the currency symbol off the text first. You can get the currency symbol from the RegionInfo.CurrencySymbol Property as well as culture.NumberFormat.CurrencySymbol and then remove that from the formatted text before passing to double.Parse.
As Mr Young points out in his comment, there is an overload of Decimal.Parse that takes a String and IFormatProvider which provide additional information about the string - such as the fact it contains a currency symbol.