Why does this snippet of code
string str = 30 + 20 + 10 + "ddd";
Console.WriteLine(str);
produces 60ddd,
and this one
string str = "ddd" + 30 + 20 + 10;
Console.WriteLine(str);
produces ddd302010?
Seems like it's very simple, but I can't get my head around it.
Please, show me direction in which I can go in order to find a detailed answer.
Thanks!
The + operators in the expression you show have equal precedence because they're the same operator, hence are evaluated left to right:
30 + 20 + 10 + "ddd"
-- + (int, int) returns (int)50
------- + (int, int) returns (int)60
------------ + (object, string) returns (string)"60ddd"
Then for the other case:
"ddd" + 30 + 20 + 10
----- + (string, object) returns (string)"ddd30"
---------- + (string, object) returns (string)"ddd3020"
--------------- + (string, object) returns (string)"ddd302010"
It's because an expression is evaluated from left side to right side. In the first example 30 + 20 + 10 gives you int + string (30 + 20 + 10) - int, "ddd" - string. In the second example "ddd" + 30 is a string "ddd30" that appends "20" and "10" to it. It's all about the order (unless you have paranthesis).
It's evaluated from left to right. The first example has the numbers first, so it starts by evaluating as numbers. Then it finds out it has to evaluate as string. The second example is the other way around. It starts with string and continues with string.
Operator + has different overloads:
int + int = int
int + string = string
string + int = string
In Following Expression:
string str = 30 + 20 + 10 + "ddd";
Console.WriteLine(str);
First 30 + 20 got evaluates both are integers so output of operator will be integer which is 50.
Then 50 + 10 will be evaluated which both are again integers so integer will be output which is 60.
Then 60 + "ddd" which is integer + string operation the operator in this case output string so 60 + "ddd" will output 60ddd.
In Following Expression:
string str = "ddd" + 30 + 20 + 10;
Console.WriteLine(str);
First "ddd" + 30 got evaluates in which string + integer operation takes place so output will be ddd30.
Then ddd30 + 20 will get evaluated in which again string + integer operation takes place so output will be ddd3020.
Then ddd3020 + 10 will get evaluated in which again string + integer operation takes place so output will be ddd302010.
It happens because, the order of operations if from left to right. But assigment is last operation.
To assing value first expression must be calculated.
Related
The following code below is concatenating the double variable .
For example first number is 2
And second is 3
It is adding them like this 2+3;
23
using System;
public static class Program
{
public static void Main()
{
double num01;
double num02;
Console.WriteLine("Add");
Console.Write("type a number: ");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("type another number: ");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("the result is " + num01 + num02);
Console.ReadKey();
}
}
You have not added 2 integers together, you have suffixed a string with 2 other numbers.
String concatenation is also 'slow'. You should use string.Format or string interpolation.
Console.WriteLine(string.Format("the result is {0}", num01 + num02) );
or
Console.WriteLine($"the result is {num01 + num02}");
The reson is that expression "the result is " + num01 + num02 is adding, which includes string, which makes the whole operation concatentaion, not addition of numbers! If at least one operand of + operator is string, it makes it concatenation.
Moreover, then every other operand is converted to string, so your numbers get converted to string and then concatenated.
To prevent that, force order of operation, so addition of your numbers is first, for example (already shown in other answers): "the result is " + (num01 + num02)
Now it will first sum two numbers, then concatenate with given string.
If you add the parentheses to the sum of the number, your code can work
double num01;
double num02;
Console.WriteLine("Add");
Console.Write("type a number: ");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("type another number: ");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("the result is " + (num01 + num02));
Console.ReadKey();
but the best practice without a doubt is:
string.Format
"It is adding them like this 2+3; 23 "
That is because you are using + in a context where it treats 2 and 3 as strings and with strings + always perform concatenation, hence the result 23
What do you need to do to fix things?
Console.WriteLine("the result is " + (num01 + num02) );
Why does the above solution works?
Short answer: Operator precedence. Parenthesis has higher precedence and is evaluated first. When that happens num01 and num02 are treated as numbers and addition takes place. And now this sum value is treated like a string in + with "the result is "
What's going on: for
"the result is " + num01 + num02
we have
"the result is " + num01 which is "the result is 1" (adding double to string)
"the result is 1" + num02 which is "the result is 12" (adding double to string)
what can you do: put (..) and have "the result is " + (num01 + num02):
num01 + num0 which is 3 (adding two doubles)
"the result is " + 3 which is "the result is 3" (adding double to string)
So you can either put (...)
Console.WriteLine("the result is " + (num01 + num02));
or (better way) use string interpolation and let .net compute the sum for you:
Console.WriteLine($"the result is {num01 + num02}");
or formatting:
Console.WriteLine("the result is {0}", num01 + num02);
I'm currently trying to add a DateTime stamp, a prefix and a unique number to a file name. My desired output is:
\ParentDirectory\Sub Directory\Another Sub Directory\Prefix- Unique Number - 11 29 2016 2 07 30 PM.xlsx
Prefix and Unique Number above will be passed into the function. I'm using the following method to achieve this:
public static string AppendDateTimeToFileName(this string fileName, string prefix, string uniqueNumber)
{
return string.Concat(
Path.GetFullPath(fileName),
Path.Combine(prefix + " - " + uniqueNumber + " - "),
Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString()
.Replace("/", " ")
.Replace(":", " ")
.Trim(),
Path.GetExtension(fileName)
);
}
I call the above method as:
string fileName = #"\\ParentDirectory\Sub Directory\Another Sub Directory\MyFile.xlsx";
string adjustedFileName = fileName.AppendDateTimeToFileName("Shipping Note", "0254900");
The output I receive is as follows:
\ParentDirectory\Sub Directory\Another Sub Directory\Shipping Note -\0254900 - 11 29 2016 2 08 10 PM
As you can see in the above output the string is incorrect, firstly I get an extra -\ and the file extension isn't coming through either. Can someone tell me where I'm going wrong please.
Here's how I'd do it
public static string AppendDateTimeToFileName(this string fileName, string prefix, string uniqueNumber)
{
return Path.Combine(
Path.GetDirectoryName(fileName),
string.Concat(
prefix,
" - ",
uniqueNumber,
" - ",
Path.GetFileNameWithoutExtension(fileName),
DateTime.Now.ToString("MM dd yyyy h mm ss tt"),
Path.GetExtension(fileName)));
}
This correctly uses Path.Combine to combine the directory from Path.GetDirectoryName and you're new concatenated file name. Note I also used a date format string instead of the replacements. You might want to consider changing that format and putting a separator between the file name and the date.
The posted version of your code give the following output:
\ParentDirectory\Sub Directory\Another Sub Directory\MyFile.xlsxShipping Note - 0254900 - MyFile29 11 2016 15 46 48.xlsx
and NOT as you posted:
\ParentDirectory\Sub Directory\Another Sub Directory\Shipping Note -\0254900 - 11 29 2016 2 08 10 PM
if your desired output is:
\ParentDirectory\Sub Directory\Another Sub Directory\Prefix- Unique Number - 11 29 2016 2 07 30 PM.xlsx
You need to move the directory into the Path.Combine and use GetDirectoryName. Also remove the line:
Path.GetFileNameWithoutExtension(fileName)
since in your desired output I don't see the old file name "MyFile".
This code:
public static string AppendDateTimeToFileName(this string fileName, string prefix, string uniqueNumber)
{
return string.Concat(
Path.Combine(Path.GetDirectoryName(fileName), prefix + " - " + uniqueNumber + " - "),
DateTime.Now.ToString()
.Replace(".", " ")
.Replace(":", " ")
.Trim(),
Path.GetExtension(fileName)
);
}
will yield the following output:
\ParentDirectory\Sub Directory\Another Sub Directory\Shipping Note - 0254900 - 29 11 2016 15 39 37.xlsx
I have a combobox made up of two numbers; inches and millimetres. At the moment it is looking hideous. I am wondering if some of the gurus here have anyway of lining the character '|' or at least make it nicer?
A bit of background info, the number inches and millimetres are separate strings which I append together like so:
Size(in) + " (In) | " + Size(mm) + " (mm)"
Possibly the cleanest way would be to format every number to have 3 decimal places for at least inches. This still won't be perfect however since the letter font width won't be perfect, to fix that you'd need to use a monospaced font.
To format to 3dp you can use the following
String.Format("{0:f3}", Size(in)) + " (In) | " + Size(mm) + " (mm)"
Since you have some values that are 2 digits before the decimal you can always use PadLeft to align these, but again this doesn't always work well without a monospaced font..
String.Format("{0:f3}", Size(in)).PadLeft(5, ' ') // or (5, '0')
Use String.PadRight(i); and String.PadLeft(i); where i is a nr. of spaces to "fill":
Example:
// Just to simplify a little, create vars:
var inches = Size(in) + " (In) ";
var mm = " + Size(mm) + " (mm)";
var formatted = inches.PadRight(15) + "|" + mm.PadLeft(15);
Example of output using 15 for the padding value (obviously, you can adjust this as needed):
43 inches | 123 cm
445554 inches | 12345 cm
I am trying to convert money to string like claim amount = 100.00 should be converted to 0010000
Court fees = 15 converted to 01500 and solictors fee = 00000(always the same number)
and total amount = 115 converted to 00011500. I dont how to convert these to zeros in the first place.
string value = Convert.ToString(ReturnValue);
Gives output :it is showing as 100.0000
can you help me where i am going wrong.
I tried this but still the same result. it is an sql query
" bat.PCN_Charge *100 ".ToString().PadLeft(7, '0') +
",[Court Fee] *100 ".ToString().PadLeft(5, '0') +
",[Solictors Fees] *100 ".ToString().PadLeft(5, '0') +
", (bat.PCN_Charge + [Court Fee]) *100".ToString().PadLeft(8, '0') +
My results are like these 10000.0000 1500 0 11500.0000
If you know your string should always have a length of seven, you can first calculate the plain int-value, then use:
value.ToString().PadLeft(7, '0')
// Example
var numericValue = 100.00;
var intValue = numericValue * 100; // 10000
var paddedResult = intValue.ToString().PadLeft(7, '0'); // 0010000
Alternatively, you can find lot's of info about padding numbers with zero here.
yes very simple
First multiply by 100 to override the decimal point.
Second use Format instead of convert
Try this
string value = string.Format("{0:0000000}", ReturnValue * 100);
Happy Coding
:)
I need to convert any number in a fixed format with a fixed amount of characters. Means 1500 and -1.5 or 0.025 need to have the same length. I also have to give the format in this form: Format = "{???}";
When i type Format = "{0000}"; i can limit 1500 to "1500", but -1.5 -> "-0001.5" means i have too much numbers after the point.
Negative sign place can be done with Format = "{ 0.0;-0.0; 0.0}".
How can i fix the count of the numbers for different numbers?
The length of the string doesn't matter, the most important is the equal length.
Examples:
1500 -> " 1500.000" or " 1500"
-1500 -> "-1500.000" or "- 1500" or " -1500"
1.5 -> " 1.500" or " 1.5"
-0.25-> " -0.250" or "- 0.25"
0.00005 -> " 0.000" or " 0"
150000-> " 150000.0" or " 150000"
15000000 " 15000000"
Edit:
I want to Format an y-Axis of a Chart. I can't use something like value.ToString("???") i need to use chartArea.AxisY.LabelStyle.Format = "{???}";
Why don't use formatting? "F3" forces 3 digits after decimal point and PadLeft ensures the overall length
Double value = 1500.0;
// 3 digits after decimal point, 9 characters length
String result = value.ToString("F3").PadLeft(9, ' ');
0 -> 0.000
1500.0 -> 1500.000
-1500.0 -> -1500.000
-0.25 -> -0.250
Another (similar) possibility is String.Format:
Double value = 1500.0;
// Put value at place {0} with format "F4" aligned to right up to 9 symbols
String result = String.Format("{0:9,F4}", value);
Try it > result = Math.Round(yourValue, 3);
Check full reference here !
you cannot achieve this by a simple format function
string result = string.Empty;
var array = dec.ToString().Split('.');
if (dec > 0)
{
result = array[0].PadLeft(9).Remove(0, 9);
if (array.Count() > 1)
{
result += '.' + array[1].PadRight(3).Remove(3);
}
}
else
{
result = "-"+array[0].PadLeft(9).Remove(0, 9);
if (array.Count() > 1)
{
result += '.' + array[1].PadRight(3).Remove(3);
}
}