Rounding up an int divided by 10 to nearest int - c#

I want to divide an int by 10 and get a whole number closest to rounded one, so
12 should give 1 and 17 should give 2
Heres my code:
int BonusValue;
int Str;
BonusValue = Convert.ToInt32(Math.Round(Convert.ToDouble(Str) / 10));
Will this work?

Yes, that should work.
It is however much easier if you add half the rounding step, in your case 5, to the integer. Then you can do simple integer division:
BonusValue = (Str+5) / 10

Use Mathf.RoundToInt:
Debug.Log(Mathf.RoundToInt(17f/10f));

That would work, but it is an inefficient way of doing it.
The best way in unity to do what you want is using the built in methods to do exactly that
BonusValue = Mathf.RountToInt(Str/10f);

It will work but what round type do you need? Check this:MidpointRounding Enumeration

Related

c# calculation only returns natural number instead of decimal [duplicate]

When I make a division in C#, it automaticaly rounds down. See this example:
double i;
i = 200 / 3;
Messagebox.Show(i.ToString());
This shows me a messagebox containing "66". 200 / 3 is actually 66.66666~ however.
Is there a way I can avoid this rounding down and keep a number like 66.6666667?
i = 200 / 3 is performing integer division.
Try either:
i = (double)200 / 3
or
i = 200.0 / 3
or
i = 200d / 3
Declaring one of the constants as a double will cause the double division operator to be used.
200/3 is integer division, resulting in an integer.
try 200.0/3.0
200 / 3 this is an integer division. Change to: 200.0 / 3 to make it a floating point division.
You can specify format string with the desired number of decimal ponits:
double i;
i = 200 / 3.0;
Messagebox.Show(i.ToString("F6"));
Though the answer is actually 66.666, what is happening is that 200 / 3 is being calculated resulting in an integer. The integer is then being placed in the float. The math itself is happening as integer math. To make it a float, use 200.0 / 3. The .0 will cause it to treat 200 as a float, resulting in floating point math.
Aside from the double vs int happening in that action, you're thinking of double as a precise unit. Try using the decimal datatype when you really care about accuracy.
More information at this answer:
decimal vs double! - Which one should I use and when?
double i = 200.0 / 3;
double i = ((double)200)/3;
What happens is the two integers perform an integer divide, and then the integer answer is assigned to the float. To avoid that, always cast one of the numbers as a double.
Try this
i = 200d/3d;
and it will not round.
200 and 3 are both integers, so the result will be an integer. Convert one of them to a decimal.
All given answers are wrong because they translate the integer division into one of kind double, which is cleanly not what was asked for (at least from a performance standpoint). The obvious answer is elementary school math, multiply by 10, add 5 and divide again, all integer.
i = (2000 / 3 + 5 ) / 10
You are catching a second division here, which is better than doing double conversions but still far from perfect. You could go even further and multiply by another factor and add other values than five, thus allowing you to use right shifting instead of dividing by 10. The exact formula for doing this is left as an exercise to the reader. (Just google "divisions with Multiply Shift")
Have a nice day.

Get last (ie endswith) 3 digits of a decimal (.NET)

I may be using Math for evil... But, in a number written as 0.7000123
I need to get the "123" - That is, I need to extract the last 3 digits in the decimal portion of a number. The least significant digits, when the first few are what most people require.
Examples:
0.7500123 -> 123
0.5150111 -> 111
It always starts from digit 5. And yes, I'm storing secret information inside this number, in the part of the decimal that will not affect how the number is used - which is the potentially evil part. But it's still the best way around a certain problem I have.
I'm wondering whether math or string manipulation is the least dodgy way of doing this.
Performance is not an issue, at all, since I'm calling it once.
Can anyone see an easy mathematical way of doing this? eg A combination of Math functions (I've missed) in .NET?
It's a strange request to be sure. But one way to get an int value of the last 3 digits is like so:
int x = (int)((yourNumber * 10000000) % 1000);
I'm going to guess there's a better way to get the information you're looking for that's cleaner, but given what you've asked for, this should work.
First Convert Your number into the String.
string s = num.ToString();
string s1 = s.Substring(s.Length - 3, 3);
Now s1 Contains Last 3 Digits Of the Number
Using modulo will get you the last 3 digits:
var d = 0.7000123m;
d = d * 10000000 % 1000;
d will now hold the value 123.
Try this:
string value= "0.1234567";
string lastthreedigit= value.Substring(value.Length - 3);

Divide by 3 and Round up (If need be) C#

I have come to a point in my game where I have to implement a feature which divides a number by 3 and makes it a whole integer. i.e. not 3.5 or 2.6 etc....
It was to be a whole number, like 3, or 5.
Does anyone know how I can do this?
Math.Round(num / 3);
or
Math.Ceiling(num / 3);
or
Math.Truncate(num / 3);
Divide by three and round up can be done with the math functions:
int xyzzy = Math.Ceiling (plugh / 3);
or, if the input is an integer, with no functions at all:
int xyzzy = (plugh + 2) / 3;
This can also be done in a more generic way, "divide by n, rounding up":
int xyzzy = (plugh + n - 1) / n;
The Ceiling function is for explicitly rounding up (towards positive infinity). There are many other variations of rounding (floor, truncate, round to even, round away from zero and so on), which can be found in this answer.
Found this which says that if you take the number to divide, add two, and divide by three you would get the correct answer. For example, 7/3 = 2.3, but (7+2)/3 = 3.

C# is rounding down divisions by itself

When I make a division in C#, it automaticaly rounds down. See this example:
double i;
i = 200 / 3;
Messagebox.Show(i.ToString());
This shows me a messagebox containing "66". 200 / 3 is actually 66.66666~ however.
Is there a way I can avoid this rounding down and keep a number like 66.6666667?
i = 200 / 3 is performing integer division.
Try either:
i = (double)200 / 3
or
i = 200.0 / 3
or
i = 200d / 3
Declaring one of the constants as a double will cause the double division operator to be used.
200/3 is integer division, resulting in an integer.
try 200.0/3.0
200 / 3 this is an integer division. Change to: 200.0 / 3 to make it a floating point division.
You can specify format string with the desired number of decimal ponits:
double i;
i = 200 / 3.0;
Messagebox.Show(i.ToString("F6"));
Though the answer is actually 66.666, what is happening is that 200 / 3 is being calculated resulting in an integer. The integer is then being placed in the float. The math itself is happening as integer math. To make it a float, use 200.0 / 3. The .0 will cause it to treat 200 as a float, resulting in floating point math.
Aside from the double vs int happening in that action, you're thinking of double as a precise unit. Try using the decimal datatype when you really care about accuracy.
More information at this answer:
decimal vs double! - Which one should I use and when?
double i = 200.0 / 3;
double i = ((double)200)/3;
What happens is the two integers perform an integer divide, and then the integer answer is assigned to the float. To avoid that, always cast one of the numbers as a double.
Try this
i = 200d/3d;
and it will not round.
200 and 3 are both integers, so the result will be an integer. Convert one of them to a decimal.
All given answers are wrong because they translate the integer division into one of kind double, which is cleanly not what was asked for (at least from a performance standpoint). The obvious answer is elementary school math, multiply by 10, add 5 and divide again, all integer.
i = (2000 / 3 + 5 ) / 10
You are catching a second division here, which is better than doing double conversions but still far from perfect. You could go even further and multiply by another factor and add other values than five, thus allowing you to use right shifting instead of dividing by 10. The exact formula for doing this is left as an exercise to the reader. (Just google "divisions with Multiply Shift")
Have a nice day.

factorial method resulting in error

I'm trying to get the factorial value of number 66, but my method resulting me an output 0. But whenever I try to get the factorial of 5, it is resulting me an output 120. Could anyone please tell me why?
public static int factorial(int n)
{
if (n == 1)
return n;
return n * factorial(n - 1);
}
Sure - factorials get very big, very fast. You're overflowing the bounds of int very quickly... and at some point you'll have multiplied by enough factors to get an overflow to 0, which will then keep the value at 0 forever.
According to a quick Google search, 66 factorial is 5.44344939 × 1092 - which is considerably more than int can handle, or even long or decimal. You could get double to handle it - you'd lose a huge amount of precision, and that would accumulate really quickly too, but at least it wouldn't overflow...
Your method overflows. See the following example:
static void Main(string[] args)
{
Console.WriteLine(factorial(66));
}
public static int factorial(int n)
{
if (n == 1)
return n;
var result = n * factorial(n - 1);
Console.WriteLine("{0} : {1}", n, result);
return result;
}
With this example, the results of each iteration is printed.
You see that at one point, result becomes 0 and this means that every iteration from that point on becomes n * 0.
You can try using BigInteger. This will give the correct result. Calculate factorials in C# contains more information on this.
66! does not fit into an int. Use BigInteger.
The problem is that the factorial of 66 is way to large to fit into an int. I think it will also we way to large to fit into a long.
As an example, factorial(20) will return 2432902008176640000
The factorial of 50 is 3.0414093202×1064 which exeeds already what a int can contain.
Use long or BigInteger for this.
You get numeric overflow, 66! ~= 5e92 which is way larger than an int can handle. Also, factorials are better calculated using a for loop.
Approximately 13 or 14 is the largest number whose factorial fits in an int... If you switch to long, it'll be aroung 18 or 19 if I recall correctly. If you wish arbitraty big numbers you'd have to write your own big arithmetic library or use an existing one :)
You need to use the appropriate data type.
In this case the Big Integer data type is probably best seeing as how fast the numbers get real big.
Here is the way you use this data type.
Right click on your project, choose the add reference menu.
Look for the system.numerics library and add it.
You then add the using clause in your code.
And then you can initialise variable with the keyword as usual.

Categories

Resources