How can I convert any string to an integer? - c#

How can i convert from example "1.234.567.890 VNĐ" or any string not in a correct number format.
output: 1234567890
I try: int.Parse, convert.ToInt32 or int.tryParse, double,.... But not working.

If all you want is the integer numbers that are contained within a string, you can just loop through the string and take all numbers.
string yourString = "1.234.567.890 VNĐ";
string tmpString = String.Empty;
for (int i = 0; i < yourString.Length; i++)
{
if (char.IsDigit(yourString, i))
{
tmpString += yourString[i];
}
}
int finalInt = int.Parse(tmpString);
char.IsDigit(string, int) (see documentation) checks if the char at position i in the string is a digit (not only 0..9, but also other numbers). If that's the case, add it to your string. At the end, you have all your numbers and can cast them to int.

Related

Getting the sum of all numbers in a character array

I have converted string to char[], but now when I try to get a total of all the numbers in the array, I get a wrong output. The goal is that if the user enters a number as a string e.g - 12, the output should be 3 i.e 1 + 2, another example - 123 should be 1+2+3 = 6.
I am new to coding. My apologies for any inconvienence.
static void Main(string[] args)
{
int sum = 0;
String num = Console.ReadLine();
char[] sep = num.ToCharArray();
for (int i = 0; i < sep.Length; i++)
{
sum += (sep[i]);
}
Console.WriteLine(sum);
Console.ReadLine();
}
You are currently adding ascii values. The ascii value of 1 is 49 and that of 2 Is 50... You need to use int.TryParse to convert from char to int.
int value;
for (int i = 0; i < sep.Length; i++)
{
if (int.TryParse (sep[i].ToString(),out value))
sum += value;
}
If you want to calculate sum of digits, you need to convert each char to int first. Char needs to be converted to string and then parsed into int. Your original code contains implicit conversion, which converts 1 and 2 into 49 and 50 (ASCII), thus the sum ends up being 99.
Try this code instead:
static void Main(string[] args)
{
int sum = 0;
String num = Console.ReadLine();
char[] sep = num.ToCharArray();
for (int i = 0; i < sep.Length; i++)
{
sum += int.Parse(sep[i].ToString());
}
Console.WriteLine(sum);
Console.ReadLine();
}
Just for fun here is a LINQ solution.
var sum = num.Select( c => int.Parse((string)c) ).Sum();
This solution takes advantage of the fact that a string is also an IEnumerable<char> and therefore can be treated as a list of characters.
The Select statement iterates over the characters and converts each one to an integer by supplying a lambda expression (that's the => stuff) that maps each character onto its integer equivalent. The symbol is typically prounced "goes to". You might pronounce the whole expression "C goes to whatever integer can be parsed from it."
Then we call Sum() to convert the resulting list of integers into a numeric sum.

Error converting string to int [duplicate]

I work on a project in C# which requires to use arabic numbers, but then it must store as integer in database, I need a solution to convert arabic numbers into int in C#.
Any solution or help please?
thanks in advance
From comments:
I have arabic numbers like ١،٢،٣،٤... and must convert to 1,2,3, or ٢٣٤ convert to 234
Updated: You can use StringBuilder for memory optimization.
private static string ToEnglishNumbers(string input)
{
StringBuilder sbEnglishNumbers = new StringBuilder(string.Empty);
for (int i = 0; i < input.Length; i++)
{
if (char.IsDigit(input[i]))
{
sbEnglishNumbers.Append(char.GetNumericValue(input, i));
}
else
{
sbEnglishNumbers.Append(input[i].ToString());
}
}
return sbEnglishNumbers.ToString();
}
Original Answer: use this Method
private string toEnglishNumber(string input)
{
string EnglishNumbers = "";
for (int i = 0; i < input.Length; i++)
{
if (Char.IsDigit(input[i]))
{
EnglishNumbers += char.GetNumericValue(input, i);
}
else
{
EnglishNumbers += input[i].ToString();
}
}
return EnglishNumbers;
}
Unfortunately it is not yet possible to parse the complete string representation by passing in an appropriate IFormatProvider(maybe in the upcoming versions). However, the char type has a GetNumericValue method which converts any numeric Unicode character to a double. For example:
double two = char.GetNumericValue('٢');
Console.WriteLine(two); // prints 2
You could use it to convert one digit at a time.
Arabic digits like ١،٢،٣،٤ in unicode are encoded as characters in the range 1632 to 1641. Subtract the unicode for arabic zero (1632) from the unicode value of each arabic digit character to get their digital values. Multiply each digital value with its place value and sum the results to get the integer.
Alternatively use Regex.Replace to convert the string with Arabic digits into a string with decimal digits, then use Int.Parse to convert the result into an integer.
A simple way to convert Arabic numbers into integer
string EnglishNumbers="";
for (int i = 0; i < arabicnumbers.Length; i++)
{
EnglishNumbers += char.GetNumericValue(arabicnumbers, i);
}
int convertednumber=Convert.ToInt32(EnglishNumbers);
This is my solution :
public static string arabicNumToEnglish(string input)
{
String[] map={"٠","١","٢","٣","٤","٥","٦","٧","٨","٩"};
for (int i = 0; i <= 9; i++)
{
input=input.Replace(map[i],i.ToString());
}
return input;
}
to get the value of a digit, substract the zero character from it, e.g in normal numeric, '1'-'0' = 1, '2'-'0' = 2. etc.
For multidigit number you can use something like this
result =0;
foreach(char digit in number)
{
result *= 10; //shift the digit, multiply by ten for each shift
result += (digit - '0)'; //add the int value of the current digit.
}
just replace the '0' with the arabic zero if your number uses Arabic character. This works for any numeric symbols, as long as 0-9 in that symbol system are encoded consecutively.
I know this question is a bit old, however I faced similar case in one of my projects and passed by this question and decided to share my solution which did work perfectly for me, and hope it will serve others the same.
private string ConvertToWesternArbicNumerals(string input)
{
var result = new StringBuilder(input.Length);
foreach (char c in input.ToCharArray())
{
//Check if the characters is recognized as UNICODE numeric value if yes
if (char.IsNumber(c))
{
// using char.GetNumericValue() convert numeric Unicode to a double-precision
// floating point number (returns the numeric value of the passed char)
// apend to final string holder
result.Append(char.GetNumericValue(c));
}
else
{
// apend non numeric chars to recreate the orignal string with the converted numbers
result.Append(c);
}
}
return result.ToString();
}
now you can simply call the function to return the western Arabic numerals.
try this extension:
public static class Extension
{
public static string ToEnglishNumbers(this string s)
{
return s.Replace("۰", "0").Replace("۱", "1").Replace("۲", "2").Replace("۳", "3").Replace("۴", "4")
.Replace("۵", "5").Replace("۶", "6").Replace("۷", "7").Replace("۸", "8").Replace("۹", "9");
}
public static int ToNumber(this string s)
{
if (int.TryParse(s.ToEnglishNumbers(), out var result))
{
return result;
}
return -1;
}
public static string ToArabicNumbers(this string s)
{
return s.Replace("0", "۰").Replace("1", "۱").Replace("2", "۲").Replace("3", "۳").Replace("4", "۴")
.Replace("5", "۵").Replace("6", "۶").Replace("7", "۷").Replace("8", "۸").Replace("9", "۹");
}
}

Counting number of char in a string and creating another string with the same number of char

So I want to be able to create a headline and underline it with for example an "=". However I want the number of "=" to match with the number of characters in the headline. Preferably I want to be able to do it with a for loop.
Here's what I have so far.
string headLine = "Example";
Console.WriteLine(headLine);
for (char i = '='; i <= headLine.Length; i += '=')
{
Console.WriteLine(i);
}
No need for any loops, just create a new string to your specifications:
string headLine = "Example";
Console.WriteLine(headLine);
Console.WriteLine(new string('=', headLine.Length));
your for loop is completely wrong, you are comparing a char which represents value with an int that represents length. Do something like this instead:
string headLine = "Example";
Console.WriteLine(headLine);
char c = '=';
for (int i=0; i < headLine.Length; i++) //from 0 to length-1 gives the full length
{
Console.Write(c);
}

Converting decimal to 16 character string with or without - sign

I am looking for a method that adds zero's up to 16 characters before a decimal, and a minus sign if the value is minus. E.g.,
18,52 becomes 000000000000001852, and
-18,52 becomes-00000000000001852
I have an idea how to implement this by using replacements and if-statements, and using the PadLeft method where characters are padded to the left to what length you specify. But I am not sure how to make it exactly.
What I have right now is this:
static string FormatDecimal(decimal d, int length = 0, char a = '0')
{
var sb = new StringBuilder();
var rounded = decimal.Round(d, 2, MidpointRounding.AwayFromZero);
if (rounded < 0)
{
sb.Append("-");
}
else
{
sb.Append("");
}
var lastPart = rounded.ToString().Replace(",", "").Replace(".", "");
var lengthMiddle = length - sb.Length - lastPart.Length;
for (int i = 0; i < lengthMiddle; i++)
{
sb.Append(a);
}
sb.Append(lastPart);
return sb.ToString();
}
When I look at the code and do Console.WriteLine(FormatDecimal(-18m, 16, '0')) I see that
The code is 1. very long, and 2. it does not work... The rounding fails and just keeps the -18 and no minus sign is added.
I would be very grateful if someone could help me out with this one!
If you want to represent two decimal digits in your string and eliminate the decimal mark, you can simply multiply your number by 100. To pad up to 16 digits, use the D format string:
decimal d = -18.52m;
string s = ((int)(d * 100)).ToString("D16");
Edit: If you only want to pad up to 15 digits for negative numbers, you could use a conditional:
decimal d = -18.52m;
int i = (int)(d * 100);
string s = i.ToString(i >= 0 ? "D16" : "D15");
Alternatively, you could express the conditional within the format string itself using section separators:
string s = i.ToString("0000000000000000;-000000000000000");
Instead of building this yourself, use what's already there. decimal.ToString() will format a number for you:
decimal d = 18.52;
string s = d.ToString("0000000000.##"); // = "0000000018.52"
decimal d = 18.00;
string s = d.ToString("0000000000.##"); // = "0000000018"
You could build your format string using the string constructor:
int length = 10;
string formatString = string.Concat(new string('0', length), ".##")
string s = d.ToString(formatString); // = "0000000018"
Note: this doesn't take care of your rounding, but I'm not clear from the question what your requirement is there.

Format string with dashes

I have a compressed string value I'm extracting from an import file. I need to format this into a parcel number, which is formatted as follows: ##-##-##-###-###. So therefore, the string "410151000640" should become "41-01-51-000-640". I can do this with the following code:
String.Format("{0:##-##-##-###-###}", Convert.ToInt64("410151000640"));
However, The string may not be all numbers; it could have a letter or two in there, and thus the conversion to the int will fail. Is there a way to do this on a string so every character, regardless of if it is a number or letter, will fit into the format correctly?
Regex.Replace("410151000640", #"^(.{2})(.{2})(.{2})(.{3})(.{3})$", "$1-$2-$3-$4-$5");
Or the slightly shorter version
Regex.Replace("410151000640", #"^(..)(..)(..)(...)(...)$", "$1-$2-$3-$4-$5");
I would approach this by having your own formatting method, as long as you know that the "Parcel Number" always conforms to a specific rule.
public static string FormatParcelNumber(string input)
{
if(input.length != 12)
throw new FormatException("Invalid parcel number. Must be 12 characters");
return String.Format("{0}-{1}-{2}-{3}-{4}",
input.Substring(0,2),
input.Substring(2,2),
input.Substring(4,2),
input.Substring(6,3),
input.Substring(9,3));
}
This should work in your case:
string value = "410151000640";
for( int i = 2; i < value.Length; i+=3){
value = value.Insert( i, "-");
}
Now value contains the string with dashes inserted.
EDIT
I just now saw that you didn't have dashes between every second number all the way, to this will require a small tweak (and makes it a bit more clumsy also I'm afraid)
string value = "410151000640";
for( int i = 2; i < value.Length-1; i+=3){
if( value.Count( c => c == '-') >= 3) i++;
value = value.Insert( i, "-");
}
If its part of UI you can use MaskedTextProvider in System.ComponentModel
MaskedTextProvider prov = new MaskedTextProvider("aa-aa-aa-aaa-aaa");
prov.Set("41x151000a40");
string result = prov.ToDisplayString();
Here is a simple extension method with some utility:
public static string WithMask(this string s, string mask)
{
var slen = Math.Min(s.Length, mask.Length);
var charArray = new char[mask.Length];
var sPos = s.Length - 1;
for (var i = mask.Length - 1; i >= 0 && sPos >= 0;)
if (mask[i] == '#') charArray[i--] = s[sPos--];
else
charArray[i] = mask[i--];
return new string(charArray);
}
Use it as follows:
var s = "276000017812008";
var mask = "###-##-##-##-###-###";
var dashedS = s.WithMask(mask);
You can use it with any string and any character other than # in the mask will be inserted. The mask will work from right to left. You can tweak it to go the other way if you want.
Have fun.
If i understodd you correctly youre looking for a function that removes all letters from a string, aren't you?
I have created this on the fly, maybe you can convert it into c# if it's what you're looking for:
Dim str As String = "410151000vb640"
str = String.Format("{0:##-##-##-###-###}", Convert.ToInt64(MakeNumber(str)))
Public Function MakeNumber(ByVal stringInt As String) As String
Dim sb As New System.Text.StringBuilder
For i As Int32 = 0 To stringInt.Length - 1
If Char.IsDigit(stringInt(i)) Then
sb.Append(stringInt(i))
End If
Next
Return sb.ToString
End Function

Categories

Resources