I have been searching around the internet for a while but haven't found what I am looking for.
Let me start with some code example:
int a = 25;
int b;
int c;
What I want to do here is I want to split the a variable and give the two values to variable b and c. The result would be int b = 2 and int c = 5, or vice versa (doesn't matter in the purpose I'm going to use this).
How can you do this?
You can use integer division and modulo for that:
int b = a / 10;
int c = a % 10;
If the variable a contains a larger number, you would first determine how many digits you want in each variable. If you for example want two digits in c, you would use 100 as the second operand in both operations.
One way you could do it is with the following code:
int input = 123845;
var digits = input.ToString().Select(x=>int.Parse(x.ToString()));
This will first of all convert your input number to a string. It then treats this string as a character array when passing to Select. It then converts the char to a string and then parses it as an int, resulting in an IEnumerable<int>.
Of note is that this won't work if your input is a negative number (it will complain about the -). It wouldn't be too hard to check for the "-" at the beginning if you wanted to though.
The other way is to continually divide by 10 getting all the digits out one by one.
public IEnumerable<int> GetDigits(int input)
{
int currentNumber = input;
List<int> digits = new List<int>();
while (currentNumber !=0)
{
digits.Add(currentNumber%10);
currentNumber = currentNumber/10;
}
digits.Reverse();
return digits;
}
This will loop through the number adding the last digit to a list as it goes. It then returns the list reversed. This does deal with negative numbers and if the input is negative all output numbers iwll be negative.
An important note is that both of these methods will deal with more than two digits input numbers.
int a = 12345;
a = Math.Abs(a);
int length = a.ToString().Length;
int[] array = new int[length];
for (int i = 0; i < length; i++)
{
array[i] = a % 10;
a /= 10;
}
Related
I'm trying to get the last two digits of an int that is a minimum of 3 digits long. Here is my (rather sloppy) attempt:
char[] number = num.ToString().ToCharArray();
int firstnum;
int secondnum;
string strLastTwoDigits = "";
int intLastTwoDigits;
firstnum = number[number.ToString().Length - 1];
secondnum = number[number.ToString().Length - 2];
strLastTwoDigits = (firstnum.ToString() + secondnum.ToString());
intLastTwoDigits = int.Parse(strLastTwoDigits);
The num variable is the number I'm trying to get the last two digits of. I'm trying to turn them into strings and use the string functions to do it, probably not the way it's done. The logic to check whether it's 3 digits or more isn't included, I don't need help with that, just getting those last two digits.
Any ideas?
Do you need those two numbers as a String? Or do you plan to convert them back to a number.
Because if you want to have a number at the end, just use the modulo- operator %.
You can find an example on how to use it here: https://www.dotnetperls.com/modulo
Edit: to state the obvious: last2 = number % 100;
Just perform a modulo operation.
var intLastTwoDigits = num % 100;
You can use the modulo of that number, it should be something like
int lastTwoDigits = num % 100;
This function will divide num / 100and gives you the rest as integer.
If you need the last to digits as int, you could just use modulo:
int lasttwo = num % 100;
the modulo operator (%) will return you the remainder of the division of one integer is by another - in this case your number divided by 100 - the remainder will always be the last two digits
If you want to use strings for that, string.Substring method will help you
var numString = num.ToString();
var strLastTwoDigits = numString.Substring(numString.Length - 2, 2);
var intLastTwoDigits = int.Parse(strLastTwoDigits);
Another (and more simpler option) is to use remainder % operator for that
int intLastTwoDigits = num % 100;
You get a remainder of division into 100, because you need the 2 last digits
I have this code:
string number = "124235245423523423", number2 = "3423525232332325423";
for(i=number.length-1;i>=0;i--){
int save = Convert.ToInt32(number[i]) + Convert.ToInt32(number2[i]);
}
That is not the complete code but my question is why can't I convert and access some value at a certain index of a string as an integer? Isn't there a straight forward approach to this? I have tried some things but it didn't work out.
You're looking for int.Parse.
int save = int.Parse(number[3].ToString());
Converting a char to Int32 returns the value of that character in the current encoding.
For more information, see the MSDN documentation for Int32.Parse.
I think that this is what you are looking for. You have to access the string by the indexer value and then convert:
int yourNumber = Convert.ToInt32(number[4].ToString());
This will give you value 3
Here is one way to do it:
string number = "124235245423523423", number2 = "3423525232332325423";
for(int i=number.Length-1;i>=0;i--){
int save = int.Parse(number[i].ToString()) + int.Parse(number2[i].ToString());
Console.WriteLine(save);
}
When Convert.ToInt32() gets a char, it returns the UTF-16 encoded code unit of the value argument (read on MSDN).
On the other hand, when it gets a string, it returns the number that string contains, or throws an exception if it's not a number.
I believe the String.ToCharArray is what you're looking for:
https://msdn.microsoft.com/en-us/library/2c7h58e5(v=vs.110).aspx
I needed a value at a certain index, here's how i did it and it works wonderfully for me:
int number = (int)char.GetNumericValue(number[index])
What I actually did is that i converted the character at the index i needed into a double first through GetNumericValue method and then i converted that double into an integer.
string number = "124235245423523423", number2 = "3423525232332325423";
for(int i=number.Length-1;i>=0;i--){
int sum = int.Parse(number[i].ToString()) + int.Parse(number2[i].ToString());
Console.WriteLine(sum);
working example
Well, since number[i] is of type char you can convert it into corresponding int either by (the most general case)
int result = (int) char.GetNumericValue(number[i]);
please notice, that char.GetNumericValue returns double, it's actual for, say, '⅜' character (3/8 corrsponds to 0.375); or if you work with ['0'..'9'] range only, all you have to do is to subtract '0':
int result = number[i] - '0';
So far your code can be implemented as
// Math.Min - number.Length and number2.Length have diffrent size
// - 1 - strings are zero-based [0..Length - 1]
for (i = Math.Min(number.Length, number2.Length) - 1; i >= 0; i--) {
int save = number[i] + number2[i] - 2 * '0';
...
}
probably you want to right align both strings:
number = "124235245423523423"
+
number2 = "3423525232332325423"
------------------------------
354... ...846
in this case you have to modify for loop:
for (int i = 0; i < Math.Max(number.Length, number2.Length); ++i) {
int sum =
(i < number.Length ? number[number.Length - i - 1] : '0') +
(i < number2.Length ? number2[number2.Length - i - 1] : '0') -
2 * '0';
...
}
I have to split a value example 44 I need the second 4. I have a way to so so now I just can figure how to make int index-able. I can make it indexable using string but I need it in int. How can I solve this issue?
Conversion that does not work
int secondDigit = num;
ld.ScaleGroup = (ScaleGroup)Convert.ChangeType(secondDigit, typeof(ScaleGroup));
int num = Convert.ToInt32(ld.ScaleGroup);
char secondDigit = num[1];//here is the issue
You can try:
int secondDigit = (int) char.GetNumericValue(num.ToString()[1]);
But a simpler option would be:
int secondDigit1 = num % 10;
If Id.ScaleGroup is a string then you can directly access its value at index 1, but remember to check the Length before accessing index.
The simpler option (involving % division) would only work for two digit numbers.
Lets say someone enter a four digit number 1234 in the console. How can you separate this number in to 1 2 3 4 using only division and the modulo operator?
public static void MathProblem()
{
Console.WriteLine("Type a four digit number:");
//Ex input: 1234
string inputNumber = Console.ReadLine();
// I'm guessing you first need to parse the
// string as an int in some way?
// And then assign it to some variable
// Now, for seperating the digits to be: 1 2 3 4,
// you can (and must) use both division (/), and the remainder (%).
// The first one will be simple, just dividing value with 1000, but
// how about the others? (Remember, % also need to be used at least
// once)
Console.Write("{0},{1},{2},{3}", value/1000, ?, ?, ?;
}
Any guidelines for making this possible for any given four digit input?
Since this seems like a homework problem, I'll simply explain the method in a few steps rather than giving you the code. Having parsed the input as an integer,
A number modulo 10 allows you to obtain its last digit.
Dividing (integer division) the number by 10 removes the last digit.
Repeat while the number is greater than 0.
int num = int.Parse(inputNumber);
Console.Write(string.Format("{0},{1},{2},{3}", (num/1000) % 100, (num/100) % 10, (num/10) % 10, num % 10));
OR
List<int> listOfInts = new List<int>();
while(num > 0)
{
listOfInts.Add(num % 10);
num = num / 10;
}
Console.Write("{0},{1},{2},{3}", listOfInts[3], listOfInts[2], listOfInts[1], listOfInts[0]);
No need to do this by division or modulo operators. Use LINQ. You can get an integer array using LINQ as below:
string inputNumber= "1234"
var intList = inputNumber.Select(digit => int.Parse(digit.ToString()));
Then, you can simply use it as you want like this:
Console.Write("{0},{1},{2},{3}", intList[0]/1000, intList[1], intList[2], intList[3]);
Or simply the way you wanted it using Division and Modulo Operator:
public int[] ParseIntString(int number)
{
List<int> digits= new List<int>();
while(number> 0)
{
digits.Add(number% 10);
number= number/ 10;
}
digits.Reverse();
return digits.ToArray();
}
I hope this helps you
int[] values;
Seperate(inputNumber, out values);
Console.Write("{0},{1},{2},{3}", values[0] / 1000, values[1], values[2], values[3]);
Console.ReadKey();
}
public static void Seperate(string numbers, out int[] values)
{
values = new int[numbers.Length];
for (int x = 0; x <= numbers.Length - 1; x++)
{
values[x] = int.Parse(numbers[x].ToString());
}
}
I just started a course in coding and had this as homework as well. I did it in excel first because I thought it was easier than running code over and over and it's more a math problem than a coding one.
Say the number is 4352.
The first digit is easy, it's the integer of the number / 1000 = 4.
Then you simply multilpy by 1000 to get 4000. Remove that and you get 352. The integer of that / 100 is 3.
Then you times that by 100 to get 300 and remove that and you get 52, the integer of that / 10 is 5. Multiply that by 10 and remove that and you're left with 2.
Just read that you must use % so I suggest getting the last number as a modular of 10
I have a problem and cant find a solution. I have numbers (decimal) like 85.12343 or 100 or 1.123324. I want to format this in a way that the result is always 13 chars long including the separator.
100 --> 100.000000000
1.123324 --> 1.12332400000
I tried with toString, but failed. How could I do this?
Thanks :)
int digits = 13;
decimal d = 100433.2414242241214M;
int positive = Decimal.Truncate(d).ToString().Length;
int decimals = digits - positive - 1; //-1 for the dot
if (decimals < 0)
decimals = 0;
string dec = d.ToString("f" + decimals);
It will not remove digits from the whole part, only the fraction, when needed.
I'd go with Kobi's answer, unless it's possible you could have more than 13 digits to start with, in which case you might need to do something like this (warning: I have not even attempted to make this efficient; surely there are ways it could be optimized if necessary):
public static string ToTrimmedString(this decimal value, int numDigits)
{
// First figure out how many decimal places are to the left
// of the decimal point.
int digitsToLeft = 0;
// This should be safe since you said all inputs will be <= 100M anyway.
int temp = decimal.ToInt32(Math.Truncate(value));
while (temp > 0)
{
++digitsToLeft;
temp /= 10;
}
// Then simply display however many decimal places remain "available,"
// taking the value to the left of the decimal point and the decimal point
// itself into account. (If negative numbers are a possibility, you'd want
// to subtract another digit for negative values to allow for the '-' sign.)
return value.ToString("#." + new string('0', numDigits - digitsToLeft - 1));
}
Example inputs/output:
Input Output
---------------------------------------
100 100.000000000
1.232487 1.23248700000
1.3290435309439872321 1.32904353094
100.320148109932888473 100.320148110
0.000383849080819849081 .000383849081
0.0 .000000000000
Quick 'n' dirty:
return (value.ToString("0.#") + "0000000000000").Substring(0, 13);
string formatted = original.ToString("0.000000000000").Remove(13);
Besides simply padding the string you can do some more elaborate math to determine the number of digits:
String FormatField(Int32 fieldWidth, Decimal value) {
var integerPartDigits =
value != Decimal.Zero ? (int) Math.Log10((Double) value) + 1 : 1;
var fractionalPartDigits = Math.Max(0, fieldWidth - integerPartDigits - 1);
return value.ToString("F" + fractionalPartDigits);
}
Note that if the value is negative or has an integer part with one less digit than the field width you will not get the desired result. However, you can modify the code to accommodate these cases based on exactly how you want to format and align these numbers.
What about
string newString;
if (original.ToString().Length >= 13)
{
newString = original.ToString().Substring(13);
}
else
{
newString = original.ToString().PadRight(13, '0');
}
int noofdecimal=3;
double value=1567.9800
value.ToString("#." + new string('0', noofdecimal));
//Result=1567.980