What do the values within the curly brackets do in this example?
{
double price = 1234.56
Console.WriteLine("TV{0:F0} is {1:C}" , 2, price);
Console.Read();
}
Basically the first number ist the index of the argument (0 means 2, 1 means price in your example).
The value after the colon is one of the Standard Numeric Format Strings, see MSDN-Docs for available options.
{0:F0} prints 2 because parameter 0 is 2 and format is Fixed Point with zero decimal places (F0)
{1:C} prints $1234,56becaus parameter 1 (price) is 1234.56 and format is Currency (C)
This example uses only Format Strings for numerics, there are also Standard Format Strings for DateTime and so on..
What do the values within the curly brackets do in this example?
They are format specifications for the values provided. Essentially, it instructs the Console.WriteLine function how to format the values as strings for output to the console. Here is a .NET fiddle that exemplifies this.
The MSDN documentation has an extensive example that shows how these work.
{0:F0} takes the given 2 int value, and simply prints it as 2, "2"
{1:C} takes the given 1234.56 double value and treats it as currency, "$1,234.45".
The 0 and 1 are significant as they are the zero-based array indicator of the location in which the parameters map to the string formatting. For example, the below demonstrates outputs from altering the arguments to better visualize the impact.
Console.WriteLine("TV{0:F0} is {1:C}", 2, price); // Prints TV2 is $1,234.56
Console.WriteLine("TV{0:F0} is {1:C}", price, 2); // Prints TV1234 is $2.00
Related
I am currently using ncalc library to do several evaluation and get the result out of it.
Right now I have found a problem where if I have a price in the format "1,234.01" it will fail to evaluate my expression.
The current workaround I've used was to remove the , but I was wondering if there is way to evaluate a currency without having to remove the , for example:
decimal price = 0;
if (!decimal.TryParse(iPrice.Text, out price))
{
MessageBox.Show("Price is not formatted correctly...");
return;
}
decimal currency = 0;
if (!decimal.TryParse(iCurrency.Text, out currency))
{
MessageBox.Show("Currency is not formatted correctly...");
return;
}
string formula = iFormula.Text.Replace("Price", price.ToString("n2")).Replace("Currency", currency.ToString("n2"));
Expression exp = new Expression(formula);
exp.Evaluate();
Evaluate fails because of the , from my price where if I remove it, it works just fine.
Sample of the formula:
(((Price+12,9)+((Price+12,9)*0,05)+(((Price+12,9)+((Price+12,9)*0,05))*0,029)+0,45)*Currency)
Stacktrace as requested:
NCalc.EvaluationException was unhandled
Message=mismatched input ',' expecting ')' at line 1:4
mismatched input ',' expecting ')' at line 1:20
mismatched input ',' expecting ')' at line 1:43
mismatched input ',' expecting ')' at line 1:59
missing EOF at ')' at line 1:77
Source=NCalc
StackTrace:
at NCalc.Expression.Evaluate()
Your question is still unclear to me, but I suspect you can fix this just by changing the format you're using when replacing. Change this:
string formula = iFormula.Text.Replace("Price", price.ToString("n2"))
.Replace("Currency", currency.ToString("n2"));
to this:
string formula = iFormula.Text.Replace("Price", price.ToString("f2"))
.Replace("Currency", currency.ToString("f2"));
That will use the "fixed point" format instead of the "number" format. You won't get grouping. Note that grouping isn't part of the number itself - it's part of how you format a number.
I'd also be tempted to specify the invariant culture explicitly, by the way.
As an aside: I haven't used NCalc myself, but if it's really forcing you to specify the numeric values in an expression as text, that sounds pretty poor. I'd expect some sort of parameterization (as per most SQL providers, for example) which should make all of this go away.
No, you cannot have a separator in your decimal literal. The compiler will confuse it with declaring multiple variables with the same type like:
decimal price = 1m, tax = 234m;
If it was a string, however, you could parse it like:
decimal price = Decimal.Parse("1,234.0", CultureInfo.InvariantCulture);
EDIT: my answer above was directed to the code sample in the first version of the question. Now that the question has been edited:
You can control the string representation of your decimal values using the Decimal.ToString(string format, IFormatProvider provider) method overload. This allows you to specify a standard or custom format string. In your case, it sounds like you need to have 2 decimal digits separated using a dot, and no group separators (no commas). So you could say:
price.ToString("F2", CultureInfo.InvariantCulture) // ex. result: "1234.56"
CultureInfo.InvariantCulture is important if you need a dot separator regardless of the current culture. If you don't specify that, the output could be "1234,56" depending on the current culture (e.g. in case of european cultures like de-DE, or fr-FR).
I'm trying to add commas to the following line of code:
Console.WriteLine(String.Format("{0, 8} {1,8} {2,8}", number, square,
cube));
How does one use alignment formatting in conjunction with adding commas?
It's this way
{0,8:N2}
N2 will format with comma based on locale.
Output sample could be useful... This: String.Format("{0, 8}, {1,8}, {2,8}", number, square, cube)); ?
Or you are looking for Number formatting that has thousands separator? Than you need to specify desired CultureInfo as first argument of the String.Format.
Try adding in the commas to the numbers before performing the alignment formatting (modifying based on your locale/culture, if necessary):
Console.WriteLine(
String.Format("{0, 8} {1,8} {2,8}",
number.ToString("#,0"),
square.ToString("#,0"),
cube.ToString("#,0")
)
);
And as Jeff points out in his comment below, you can also accomplish this by including the comma formats inline with the alignment formatting (the first part of each format block gives the alignment, the second part formats the string):
Console.WriteLine("{0,8:#,0} {1,8:#,0} {2,8:#,0}", number, square, cube);
I want to format an integer i (-100 < i < 100), such that:
-99 formats as "-99"
9 formats as "+09"
-1 formats as "-01"
0 formats as "+00"
i.ToString("00")
is close but does not add the + sign when the int is positive.
Is there any way to do this without explicit distinguishing between
i >= 0 and i < 0?
Try this:
i.ToString("+00;-00;+00");
When separated by a semicolon (;) the first section will apply to positive values, the second section will apply to negative values, the third section will apply to zero (0).
Note that the third section can be omitted if you want zero to be formatted the same way as positive numbers. The second section can also be omitted if you want negatives formatted the same as positives, but want a different format for zero.
Reference: MSDN Custom Numeric Format Strings: The ";" Section Separator
You might be able to do it with a format string like so..
i.ToString("+00;-00");
This would produce the following output..
2.ToString("+00;-00"); // +02
(-2).ToString("+00;-00"); // -02
0.ToString("+00;-00"); // +00
Take a look at the MSDN documentation for Custom Numeric Format Strings
Try something like this:
i.ToString("+00;-00");
Some examples:
Console.WriteLine((-99).ToString("+00;-00")); // -99
Console.WriteLine(9.ToString("+00;-00")); // +09
Console.WriteLine((-1).ToString("+00;-00")); // -01
Console.WriteLine((0).ToString("+00;-00")); // +00
Im new to C# programming. Can someone please explain the following code:
Console.WriteLine( "{0}{1,10}", "Face", "Frequency" ); //Headings
Console.WriteLine( "{0,4}{1,10}",someval,anotherval);
I understand that this prints two columns of values with the headings given, and {0} refers to the first argument given. But what is the meaning of the format strings of the form {x,y} ?
It adds padding to the left. Very useful for remembering the various string formatting patterns is the following cheat sheet:
.NET String.Format Cheat Sheet
Positive values add padding to the left, negative add padding to the right
Sample Generates
String.Format("[{0, 10}]", "Foo"); [∙∙∙∙∙∙∙Foo]
String.Format("[{0, 5}]", "Foo"); [∙∙Foo]
String.Format("[{0, -5}]", "Foo"); [Foo∙∙]
String.Format("[{0, -10}]", "Foo"); [Foo∙∙∙∙∙∙∙]
When you see {x,y}, x represents the argument's index and y the alignment, as specified here. The complete syntax is the following:
{index[,alignment][:formatString]}
This is a padding value...if the argument isn't the length that is specified, it puts spaces in.
E.g. if you had {0,10} and the argument for {0} was "Blah", the actual value printed would be "Blah<SPACE><SPACE><SPACE><SPACE><SPACE><SPACE>"...Blah, with 6 extra spaces to make up a string of 10 length
ps - not sure how to put actual spaces in...need to look up SO faq no doubt
I hate to ask such a dumb question, but I'm just starting out, so here goes.
myString = "2 to 2.5 power is " + Math.Pow(2, 2.5);
I want to format the resulting number to 4 decimal places and show the string in a MessageBox. I can't seem to figure this out or find the answer in the book. Thanks!
The ToString method should do the trick. You might need to look it up in the MSDN to find more formatting options.
Math.Pow(2, 2.5).ToString("N4")
To show a string in a MessageBox you use MessageBox.Show. In particular, there is an overload accepting a single string parameter that will be displayed in the MessageBox. Thus, we need
string s = // our formatted string
MessageBox.Show(s);
Now, let's figure out what our string is. A useful method here is String.Format. A useful reference here is the Standard Numeric Format Strings page on MSDN. In particular, I draw your attention to the fixed-point specifier "F" or "f":
The fixed-point ("F) format specifier converts a number to a string of the form "-ddd.ddd…" where each "d" indicates a digit (0-9). The string starts with a minus sign if the number is negative.
The precision specifier indicates the desired number of decimal places.
Thus, we want
double result = Math.Pow(2, 2.5);
string s = String.Format("2 to 2.5 power is {0:F4}", result);
so, putting it all together,
double result = Math.Pow(2, 2.5);
string s = String.Format("2 to 2.5 power is {0:F4}", result);
MessageBox.Show(s);
string.format("2 to 2.5 power is {0:0.000}", Math.Pow(2, 2.5));
Math.Pow(2, 2.5).ToString("N4")
is what you want I think.
more formatting options
It's not a dumb question: several of the other answers are wrong.
MessageBox.Show(string.Format("2 to 2.5 power is {0:F4}", Math.Pow(2, 2.5)));