cannot convert "-1,37739,38739" to integer C# [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
I have tried to convert the string "-1,37739,38739" into an integer in order to pass the integer into a predefined method.
I'm getting System.FormatException: 'Input string was not in a correct format.'
var dc1 = Convert.ToInt32(item.Path.ToString());
he item.Path come from a query value predefined as a string, I have to convert that string into an integer, it's coming with the above mentioned string value

-1,37739,38739 is - reformatted - -13,773,938,739; int.MinValue (the most negative value a 32-bit signed integer can represent) is -2,147,483,648 - so: it won't fit. Try long instead of int, i.e. ToInt64.
You may also need to specify an explicit culture (depending on your locale), and be a little more... forgiving re group separators:
if (long.TryParse("-1,37739,38739",
NumberStyles.Integer | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture, out var val))
{
Console.WriteLine(val); // works
}

This not a surprise.
1st : -1,37739,38739 is not properly formatted. This should be either
-13773938739
or
-13,773,938,739 (or -13 773 938 739 depending on your locale)
2nd: Int32 is an integer based on 32 bits which gives min and max values -2,147,483,648 and 2,147,483,647
See documentation here Int32
If you want to convert a string which is not controlled upfront, then I would suggest you "clean" it
string item = "-1,37739,38739";
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
item = rgx.Replace(item, "");
and maybe convert to Int64
var dc1 = Convert.ToInt64(item);
If you want to avoid exception, you also can try to parse the string (once cleaned)
if (Int64.TryParse(item, out var dc1))
{
// doSomething
}
else
{
// handle error
}

string item = "-1,37739,38739";
var munyamatindike=Convert.ToInt32(item);
the above code snippet should fix the error.enter image description here

Related

C# three part format display original value [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 1 year ago.
Improve this question
I am trying to display the original value in C# three part display format. I got unexpected result + 29291221321. I am expecting + 29.12121321. Is this a bug or what am I doing wrong?
double value1 = 29.1221321;
string formattingString = $"+ {value1}; - {value1}; 0";
// returns "+29.1221321; -29.1221321; 0"
Console.WriteLine(value1.ToString(formattingString));
// returns "+ 29291221321"
Please refer to why i call ToString at the end. It is something known as three part format to separate outcome quickly based on +, - and 0 value
https://diptimayapatra.wordpress.com/2014/01/13/3-part-format-of-numbers-in-c/
Note:
I am not expecting to hardcode by specify x numbers of # after decimal places. Please advise if there is a better method of displaying the original decimal value in three part format
string formattingString = "+ #.############; - #.############; 0";
Please advise if there is a better method of displaying the original decimal value in three part format
# is already the best way to express what you want, since it will omit non-significant zeros at the end. A double has about 15 to 17 significant digits, so you can put 17 # at the end of your format specifier to get the original value.
double value1 = 1.23456;
string formattingString = "+ #.#################; - #.#################; 0";
Console.WriteLine(value1.ToString(formattingString));
Console.WriteLine((-value1).ToString(formattingString));
Console.WriteLine(0.ToString(formattingString));
Output (note the leading spaces, because you have spaces in your format specifier):
+ 1,23456
- 1,23456
0
Check that for a double value with more digits
double value1 = 1.2345678901234567890123; // too many digits for a double
and compare it to the output of
Console.WriteLine(value1);
You're putting the value into the format specifier instead of your specifier:
string formattingString = $"+ {value1}; - {value1}; 0";
Your snippet should instead look like this:
double value1 = 29.1221321;
string formattingString = $"+ #.############; - #.############; 0";
Console.WriteLine(value1.ToString(formattingString));
With the added understanding that you do not want to use the hard coded number of decimal places (which is understandable given the precision available with double), I'm not aware of a way using interpolation. I'd recommend a simple extension method for it:
public static string ToSignedString(this double value) {
if (value < 0)
return $"-{value}";
else if (value > 0)
return $"+{value}";
return "0";
}
I don't typically recommend extension methods, but I believe your reasoning for not wanting hard coded decimal places is perhaps the need for the code to be concise due to heavy use.
double value = 29.1221321;
Console.WriteLine(value.ToSignedString());
Not the most graceful solution, but it would work.
You try to reformat Value1 another time in the Console.WriteLine
Change it to :
Console.WriteLine(formattingString);

C# parse int from different locale [duplicate]

This question already has answers here:
Thousand separated value to integer
(4 answers)
Closed 3 years ago.
I know, there are other questions like this
e.g. Convert number into culture specific
But I am having a hard time and even the answer doesn't work for me. Still getting
System.FormatException: 'Input string was not in a correct format.'
My current/system locale is de and I am parsing an en int. Whatever I tried so far (including answers from previous quesions, does not work.
So, what am I missing?
string numberStr = "1,111"; // one thousand one hundred eleven
//int result = int.Parse(numberStr);
//int result = int.Parse(numberStr, CultureInfo.GetCultureInfo("en-US").NumberFormat);
//int result = int.Parse(numberStr, CultureInfo.InvariantCulture);
//int result = int.Parse(numberStr, CultureInfo.InvariantCulture.NumberFormat);
//int result = int.Parse(numberStr, CultureInfo.GetCultureInfo("en-UK").NumberFormat);
int result = int.Parse(numberStr, CultureInfo.GetCultureInfo("en"));
Console.WriteLine(result);
Your problem is simply that int.Parse(string) and int.Parse(string, IFormatProvider) don't allow a thousands separator.
You can see this in the Remarks section of the doc:
The s parameter contains a number of the form:
[ws][sign]digits[ws]
You can however, use the int.Parse(string, NumberStyles), overload, which lets you specify NumberStyles.
If we peek at the source for int.Parse(string), we can see that it effectively calls int.Parse(string, NumberStyles.Integer).
If you look at the docs for NumberStyles, we want Integer, but also AllowThousands. We don't want to go as far as Number, because that includes AllowDecimalPoint, and integers can't have decimal points.
int result = int.Parse("1,111", NumberStyles.Integer | NumberStyles.AllowThousands);
You probably also want to specify a culture, because the thousands separator depends on culture (e.g. German uses . as the thousands separator). The invariant culture uses ,, as does en:
int result = int.Parse(
"1,111",
NumberStyles.Integer | NumberStyles.AllowThousands,
CultureInfo.InvariantCulture);
If you allow thousands separators, it will work:
int.Parse("1,111", NumberStyles.AllowThousands, CultureInfo.GetCultureInfo("en"));
// 1111

getting precision to 5 in C# for decimal data type [duplicate]

This question already has answers here:
Adjusting decimal precision, .net
(7 answers)
Closed 4 years ago.
I am diving 2 decimal number and want value upto 5 precision. below is my code.
decimal postiveTotal = 3,totalLenght = 6;
decimal postiveFractionResult = postiveTotal / totalLenght;
I m expecting 0.50000 but I am getting 0.5
C# number display type like decimal will always strip the appended 0 - there is no difference between 0.5 and 0.50.
If you want to have the output correctly formatted you need to use a string format identifier:
Custom number format identifier:
Console.WriteLine($"{postiveFractionResult:0.00000}");
Standard number format identifier:
Console.WriteLine($"{postiveFractionResult:F5}");
Assignment to variables:
// using string interpolation
string result = $"{postiveFractionResult:0.00000}";
// using string.format explicite
string result = string.Format("{0:0.00000}", postiveFractionResult);
You can find more information on string format here.
Standard Numeric Format
Custom Numeric Format Strings
EDIT
As noted by Daisy Shipton there is a difference when declaring a variable either by 0.5M or 0.50M. A little test with the different declaration shows that the additional defined 0 is also preserved through calculation:
var result = 1.25m * 0.5m; // 6.25M
var result1 = 1.250m * 0.5m; // 0.6250M
var result2 = 1.250m * 0.50000m; // 0.62500000M
var result3 = 1.25000m * 0.5m; // 0.625000M
var result4 = 1.25000m * 0.50000m; // 0.6250000000M
Please see also the following so post which has an explanation about this behavior. Sadly the links are broken and I could not find the correct ECMA link due to the website being currently offline.

How i can get input from user where the two inputs are separated by spaces? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How i can get input from user where the two inputs are separated by space?
I tried doing this with Conver.ToInt32(Console.ReadLine());But it is showing format exception.
Please tell whether there is some other way of getting input from user.
Please help!
Thank you for reading my problem.
Ex:
input:
10 2
input is in the above format.
The value 10 & 2 should be stored in different variables.
string[] inputs =TextBoX1.Text.Split(" ");
String first = inputs[0].ToString();
String second = inputs[1].ToString();
string[] inputs =Console.ReadLine().Split(null);
int input1=TryParse(inputs[0]);
int input2=TryParse(inputs[1]);
Console.ReadLine() will only return values once the user enters a new-line (IE. presses return).
To get what you're after, you might consider using Console.ReadKey() or Console.Read() in order to get individual characters.
Such that your code would look something like:
public int GetNextNumber()
{
char nextChar;
string numberString = string.Empty;
while (!char.IsWhiteSpace(nextChar = (char)Console.Read())
numberString += nextChar;
int result;
if (!int.TryParse(numberString, out result))
throw new InvalidCastException("Specified string is not an integral");
return result;
}
You can then use that method to read each individual number from the console, as the user enters it.
You could also do a Console.ReadLine() and split the resulting string to get the numbers like some of the others suggested
Hope this helps.
Because I do not see the actual code you tried I can just assume you did something like:
int input = Convert.ToInt32(Console.ReadLine());
and the actual input was "10 2", which is a string.
The error occured when the method tried to convert the empty space to an int.
You need to save the input as a string variable, then split the string variable with empty spaces as seperator. You can save the result as an string array (string[]) and then convert each array element of the string[] to an int.
Reading the input for your code:
string input = Console.Readline();
Split method for your code:
string[] stringArray= input.Split(' ');
Convert each string to an int for your code:
List<int> integerList = new List<int>();
foreach (string str in array)
{
integerList.Add(Convert.ToInt32(str));
}
Note, that this would also work for an input with more than 2 numbers, for example "10 2 17 3 19 27" and you do not need an own variable for each input part because you add each value to a list. Why a list ? because the size is dynamic. Your problem would also work with an array instead of a list because at the moment you split your string you know the size the intArray would need but a list is more comfortable.

Convert String to Integer [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
how can I convert String to Int ?
Hi,
I have the following problem converting string to an integer:
string str = line.Substring(0,1);
//This picks an integer at offset 0 from string 'line'
So now string str contains a single integer in it. I am doing the following:
int i = Convert.ToInt32(str);
i should be printing an integer if I write the following statement right?
Console.WriteLine(i);
It compiles without any error but gives the following error on runtime:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
Additional information: Input string was not in a correct format.
Any help please?
Rather than using Convert.ToInt32(string) you should consider using Int32.TryParse(string, out int) instead. The TryParse methods are there to help deal with user-provided input in a safer manner. The most likely cause of your error is that the substring you are returning has an invalid string representation of an integer value.
string str = line.Substring(0,1);
int i = -1;
if (Int32.TryParse(str, out i))
{
Console.WriteLine(i);
}
FormatException
value does not consist of an optional
sign followed by a sequence of digits
(0 through 9).
The exception that is thrown when the
format of an argument does not meet
the parameter specifications of the
invoked method.
You can use Int32.TryParse if you don't want to generate an exception like this.
Int32.TryParse: Converts the string representation of
a number to its 32-bit signed integer
equivalent. A return value indicates
whether the operation succeeded.
It's entirely possible there is some whitespace in there. Try running something akin to trim() (I'm not sure what language you're in) that will strip the white space. Also, try printing out the string to make sure you actually have the right part of it. We've all done that :)
It's likely that your input is not a valid format. Try this instead. If the number is not valid, it should output an error.
Keep in mind that the string should consist of an optional sign followed by a number.
string line = "23"; // or whatever.
string str = line.Substring(0,1);
int i = 0;
if (Int32.TryParse(str, out i)) {
Console.WriteLine(i);
} else {
Console.WriteLine ("Error converting '" + line + "', '" + str + "'.");
}
One thing you may be seeing is the user entering "-1" for example. If you do the substring(0,1) on that, you'll only get "-" which isn't really valid.
Are you sure that the value returned in str is an int, set a debug point if your using visual studio. Ive got a feeling your problem maybe that your not actually returning an integer. Try:
line.Trim().Substring(0,1);
This will remove any whitespace.

Categories

Resources