MVC - Controller - Make a Simple Math Calculation - Variable + 1 - c#

I have a little problem to make a simple math calculation in the controller.
what I try to do is add +1 to a number of a variable.
Here is an example for you to understand better what I try to do:
var a= formcollection["Id_this"];
var next = a + 1;
Note: the value of "Id_this" is "1".
The result I need for the variable next is 2
My problem is that the result of the variable next is "12".

a is a string. Adding a number to a string results in the number being converted to a string and being concatenated.
To make it work, you first need to convert a to a number:
var next = Convert.ToInt32(a) + 1;

Reason is you are doing string concatenation. Try this safe approach:
int number;
int next = 0;
if(Int32.TryParse(formcollection["Id_this"], out number))
{
next = number + 1;
}
else
{
//formcollection["Id_this"] is not a number
}

like this :
var next = int.Parse(a) + 1;

Related

Reducing a BigInteger value in C#

I'm somewhat new to working with BigIntegers and have tried some stuff to get this system working, but feel a little stuck at the moment and would really appreciate a nudge in the right direction or a solution.
I'm currently working on a system which reduces BigInteger values down to a more readable form, and this is working fine with my current implementation, but I would like to further expand on it to get decimals implemented.
To better give a picture of what I'm attempting, I'll break it down.
In this context, we have a method which is taking a BigInteger, and returning it as a string:
public static string ShortenBigInt (BigInteger moneyValue)
With this in mind, when a number such as 10,000 is passed to this method, 10k will be returned. Same for 1,000,000 which will return 1M.
This is done by doing:
for(int i = 0; i < prefixes.Length; i++)
{
if(!(moneyValue >= BigInteger.Pow(10, 3*i)))
{
moneyValue = moneyValue / BigInteger.Pow(10, 3*(i-1));
return moneyValue + prefixes[i-1];
}
}
This system is working by grabbing a string from an array of prefixes and reducing numbers down to their simplest forms and combining the two and returning it when inside that prefix range.
So with that context, the question I have is:
How might I go about returning this in the same way, where passing 100,000 would return 100k, but also doing something like 1,111,111 would return 1.11M?
Currently, passing 1,111,111M returns 1M, but I would like that additional .11 tagged on. No more than 2 decimals.
My original thought was to convert the big integer into a string, then chunk out the first few characters into a new string and parse a decimal in there, but since prefixes don't change until values reach their 1000th mark, it's harder to tell when to place the decimal place.
My next thought was using BigInteger.Log to reduce the value down into a decimal friendly number and do a simple division to get the value in its decimal form, but doing this didn't seem to work with my implementation.
This system should work for the following prefixes, dynamically:
k, M, B, T, qd, Qn, sx, Sp,
O, N, de, Ud, DD, tdD, qdD, QnD,
sxD, SpD, OcD, NvD, Vgn, UVg, DVg,
TVg, qtV, QnV, SeV, SPG, OVG, NVG,
TGN, UTG, DTG, tsTG, qtTG, QnTG, ssTG,
SpTG, OcTG, NoTG, QdDR, uQDR, dQDR, tQDR,
qdQDR, QnQDR, sxQDR, SpQDR, OQDDr, NQDDr,
qQGNT, uQGNT, dQGNT, tQGNT, qdQGNT, QnQGNT,
sxQGNT, SpQGNT, OQQGNT, NQQGNT, SXGNTL
Would anyone happen to know how to do something like this? Any language is fine, C# is preferable, but I'm all good with translating. Thank you in advance!
formatting it manually could work a bit like this:
(prefixes as a string which is an char[])
public static string ShortenBigInt(BigInteger moneyValue)
{
string prefixes = " kMGTP";
double m2 = (double)moneyValue;
for (int i = 1; i < prefixes.Length; i++)
{
var step = Math.Pow(10, 3 * i);
if (m2 / step < 1000)
{
return String.Format("{0:F2}", (m2/step)) + prefixes[i];
}
}
return "err";
}
Although Falco's answer does work, it doesn't work for what was requested. This was the solution I was looking for and received some help from a friend on it. This solution will go until there are no more prefixes left in your string array of prefixes. If you do run out of bounds, the exception will be thrown and handled by returning "Infinity".
This solution is better due to the fact there is no crunch down to doubles/decimals within this process. This solution does not have a number cap, only limit is the amount of prefixes you make/provide.
public static string ShortenBigInt(BigInteger moneyValue)
{
if (moneyValue < 1000)
return "" + moneyValue;
try
{
string moneyAsString = moneyValue.ToString();
string prefix = prefixes[(moneyAsString.Length - 1) / 3];
BigInteger chopAmmount = (moneyAsString.Length - 1) % 3 + 1;
int insertPoint = (int)chopAmmount;
chopAmmount += 2;
moneyAsString = moneyAsString.Remove(Math.Min(moneyAsString.Length - 1, (int)chopAmmount));
moneyAsString = moneyAsString.Insert(insertPoint, ".");
return moneyAsString + " " + prefix;
}
catch (Exception exceptionToBeThrown)
{
return "Infinity";
}
}

Incremental counting and saving all values in one string

I'm having trouble thinking of a logical way to achieve this. I have a method which sends a web request with a for loop that is counting up from 1 to x, the request counts up until it finds a specific response and then sends the URL + number to another method.
After this, saying we got the number 5, I need to create a string which displays as "1,2,3,4,5" but cannot seem to find a way to create the entire string, everything I try is simply replacing the string and only keeping the last number.
string unionMod = string.Empty;
for (int i = 1; i <= count; i++)
{
unionMod =+ count + ",";
}
I assumed I'd be able to simply add each value onto the end of the string but the output is just "5," with it being the last number. I have looked around but I can't seem to even think of what I would search in order to get the answer, I have a hard-coded solution but ideally, I'd like to not have a 30+ string with each possible value and just have it created when needed.
Any pointers?
P.S: Any coding examples are appreciated but I've probably just forgotten something obvious so any directions you can give are much appreciated, I should sleep but I'm on one of those all-night coding grinds.
Thank you!
First of all your problem is the +=. You should avoid concatenating strings because it allocates a new string. Instead you should use a StringBuilder.
Your Example: https://dotnetfiddle.net/Widget/qQIqWx
My Example: https://dotnetfiddle.net/Widget/sx7cxq
public static void Main()
{
var counter = 5;
var sb = new StringBuilder();
for(var i = 1; i <= counter; ++i) {
sb.Append(i);
if (i != counter) {
sb.Append(",");
}
}
Console.WriteLine(sb);
}
As it's been pointed out, you should use += instead of =+. The latter means "take count and append a comma to it", which is the incorrect result you experienced.
You could also simplify your code like this:
int count = 10;
string unionMod = String.Join(",", Enumerable.Range(1, count));
Enumerable.Range generates a sequence of integers between its two parameters and String.Join joins them up with the given separator character.

how to get values from text using .IndexOf and .Substring in c#?

I need to make a summation for several values out from string variable,
Here is my variable:
string strBillHeader = "Invoice Details
INVOICE_DATE,INVOICE_DESCRIPTION,VALUE,FROM_DATE,TO_DATE
01/11/2014,New Corpbundle 7,7,01/11/2014,30/11/2014
01/11/2014,New Corpbundle 7,-7,01/11/2014,30/11/2014
01/11/2014,New Corpbundle 7,7,01/11/2014,30/11/2014
01/11/2014,Missed Call ALERT with Offer,2,01/11/2014,30/11/2014"
I need to get out the VALUES which are (7,-7,7,2) in this case? and to get 9 as a result.
I tried to do it this way:
for (int x = 4; x <= countCommas - 3; x += 4)
{
int firstCommaIndex = strBillHeader.IndexOf(',', strBillHeader.IndexOf(',') + x);
int secondCommaIndex = strBillHeader.IndexOf(',', strBillHeader.IndexOf(',') + (x + 1));
string y = strBillHeader.Substring(firstCommaIndex + 1, 1);
chargeAmount = Convert.ToInt32(y);
//chargeAmount = Int32.Parse(strBillHeader.Substring(firstCommaIndex, secondCommaIndex - firstCommaIndex));
TotalChargeAmount += ChargeAmount;
//string AstrBillHeader = strBillHeader.Split(',')[0];
}
but it did not work since I keep getting 'V' in the y variable.
Any help will be appreciated
If those commas and newlines are always there, this should work:
var lines = strBillHeader.Split(Environment.NewLine).Skip(2);
int total = lines.Split(',').Sum(line => Convert.ToInt32(line[2]));
So, you split the invoice into lines and discard the first 2 ("Invoice Details" and "INVOICE_DATE,INVOICE_DESCRIPTION,VALUE,FROM_DATE,TO_DATE"). Then you split each line on the commas, and take the third value - the first is a date, the second is the "New Corpbundle 7" part, the third is your value. You parse that value as an int, and sum the whole lot.
You may find you need to filter out the lines properly, rather than just assuming you can skip the first two and use the rest, but this should get you started.

Increase an int by one

On another page I've said that nr = 0
var number = this.NavigationContext.QueryString["nr"];
int Nr = Convert.ToInt16(number);
And this works, Nr = 0
Now I want to upgrade Nr by one:
int next = Nr++;
Unfortunately this doesn't work... next = 0 too, but it supposed to be 1.
Could someone explain to me what I'm doing wrong?
Nr++ increments and returns the original value of Nr.
++Nr increments and returns the new value of Nr. So what you want is:
int next = ++Nr;
In C# (or C++), the statement
int next = Nr++;
translates to, "assign the value of Nr to variable next, and then increment Nr by 1.
If you want Nr to increment first, your statement should look like this:
int next = ++Nr;
Here is the definition of the ++ operator: http://msdn.microsoft.com/en-us/library/36x43w8w.aspx
the problem is ...Nr is incremented after Nr set to next use next=Nr+1;
There are two increment operators - pre-increment ++c and post-increment c++.
var x = ++c; is equivalent to
c = c + 1;
var x = c;
while var x = c++; is equivalent to
var x = c;
c = c + 1;
and therefore x either receives the value before or after c got incremented.

How to go about storing multiple values from a loop, and displaying asterisks based on input

This question asks to write a program that accepts input for five 'stores'. The input should ideally be a range from 100 to 2000. Each input should be divided by 100, and have that amount displayed in asterisks (i.e. 500 is *, etc.). I believe I have the first part, but I've got no idea how to go about doing the rest. I cannot use arrays, as I have not learned them yet, and I want to be learn this myself instead of just copy-pasting from another student. So far, I only have
int loop;
loop = 1;
while (loop <= 5)
{
string input1;
int iinput1, asteriskcount1;
Console.WriteLine("Input number of sales please!");
input1 = Console.ReadLine();
//store value?
loop = loop + 1;
input1 = Convert.ToInt32(input1);
asteriskcount1 = iinput1 / 10;
}
Not sure if I understand what you're trying to do. But maybe this will help. This is untested, but it should do what I THINK you are asking, but I am unsure what you wanted done with the asterisks. Please explain more if this isn't what you were getting at.
string Stored = "";
for (int i=0; i < 5; i++;)
{
string input1;
int iinput1, asteriskcount1;
Console.WriteLine("Input number of sales please!");
input1 = Console.ReadLine();
//Adds to existing Stored value
Stored += input1 + " is ";
//Adds asterisk
iinput1 = Convert.ToInt32(input1);
asteriskcount1 = iinput1 / 100;
for(int j = 0; j < asteriskcount1; j++)
{
Stored += "*";
}
//Adds Comma
if(i != 4)
Stored += ",";
}
Console.WriteLine(Stored); //Print Result
Don't want to write it out for you but here's some thoughts ...
first, you can do a for loop for the 5 stores:
for (int loop = 0; loop < 5; loop++)
You'll probably want asterickCount (not asterickCount1) since you're in a loop. You'll also want to divide by 100 since you're range is up to 2000 and you have 80 chars on a console. That means it will print up to 20 astericks.
You'll want a PrintAstericks(int count); function that you call right after calculating the asterickCount that you call. That function simply loos and calls Console.Write (not WriteLine) to write an asterick n times (new string has overload to take char and count).
But, that pattern will print the astericks after you take each input. If you want the pattern to be (1) accept the counts for the five stores and then (2) print the asterick rows for all five, you'll need an array with 5 slots to store the inputs then loop through the array and print the asterick rows.
Finally, you'll want to put some validation on the inputs. Look at Int32.TryParse:
http://msdn.microsoft.com/en-us/library/bb397679.aspx
Super easy
int asteriskCount = int.Parse(input1)/ 100;
string output = new string('*', asteriskCount );

Categories

Resources