C# - Decimal to integer and round depending on value - c#

I'm trying convert a decimal into integer and want to round the value up or down depending on the situation.
Basically example is:
12/3 = 4 so should round to 4
11/3 = 3.66666 so should round to 4
10/3 = 3 = 3.33333 so should round to 3
9/3 = 3 so should round to 3
Whatever I found on the internet always rounds down or always rounds up, never makes a judgment call based on the numbers.

If x is the number you want to round and you want the "normal" rounding behavior (so that .5 always gets rounded up), you need to use Math.Round(x, MidpointRounding.AwayFromZero). Note that if you are actually computing fractions and the numerator and denominator are integers, you need to cast one of them to double first (otherwise, the division operator will produce an integer that is rounded down), and that if you want the result to be an int, you need to cast the result of Round():
int a = 5;
int b = 2;
double answer = (int) Math.Round(a / (double) b, MidpointRounding.AwayFromZero);

Math.Round(value) should do what you want. Examples console app code to demonstrate:
Console.Write("12 / 3 = ");
Console.WriteLine((int)Math.Round(12d / 3d));
Console.WriteLine();
Console.Write("11 / 3 = ");
Console.WriteLine((int)Math.Round(11d / 3d));
Console.WriteLine();
Console.Write("10 / 3 = ");
Console.WriteLine((int)Math.Round(10d / 3d));
Console.WriteLine();
Console.Write("9 / 3 = ");
Console.WriteLine((int)Math.Round(9d / 3d));
Console.WriteLine();
Console.ReadKey();

Does Math.Round(d) do what you require?
Return Value:
The integer nearest parameter d. If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned. Note that this method returns a Decimal instead of an integral type.
Check out the Round reference page

You could try this
Math.Round(d, 0, MidpointRounding.AwayFromZero)
Sometime, people add 0.5 to the number before converting to int.

Related

Dividing two numbers always returns 0 [duplicate]

How come dividing two 32 bit int numbers as ( int / int ) returns to me 0, but if I use Decimal.Divide() I get the correct answer? I'm by no means a c# guy.
int is an integer type; dividing two ints performs an integer division, i.e. the fractional part is truncated since it can't be stored in the result type (also int!). Decimal, by contrast, has got a fractional part. By invoking Decimal.Divide, your int arguments get implicitly converted to Decimals.
You can enforce non-integer division on int arguments by explicitly casting at least one of the arguments to a floating-point type, e.g.:
int a = 42;
int b = 23;
double result = (double)a / b;
In the first case, you're doing integer division, so the result is truncated (the decimal part is chopped off) and an integer is returned.
In the second case, the ints are converted to decimals first, and the result is a decimal. Hence they are not truncated and you get the correct result.
The following line:
int a = 1, b = 2;
object result = a / b;
...will be performed using integer arithmetic. Decimal.Divide on the other hand takes two parameters of the type Decimal, so the division will be performed on decimal values rather than integer values. That is equivalent of this:
int a = 1, b = 2;
object result = (Decimal)a / (Decimal)b;
To examine this, you can add the following code lines after each of the above examples:
Console.WriteLine(result.ToString());
Console.WriteLine(result.GetType().ToString());
The output in the first case will be
0
System.Int32
..and in the second case:
0,5
System.Decimal
I reckon Decimal.Divide(decimal, decimal) implicitly converts its 2 int arguments to decimals before returning a decimal value (precise) where as 4/5 is treated as integer division and returns 0
You want to cast the numbers:
double c = (double)a/(double)b;
Note: If any of the arguments in C# is a double, a double divide is used which results in a double. So, the following would work too:
double c = (double)a/b;
here is a Small Program :
static void Main(string[] args)
{
int a=0, b = 0, c = 0;
int n = Convert.ToInt16(Console.ReadLine());
string[] arr_temp = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(arr_temp, Int32.Parse);
foreach (int i in arr)
{
if (i > 0) a++;
else if (i < 0) b++;
else c++;
}
Console.WriteLine("{0}", (double)a / n);
Console.WriteLine("{0}", (double)b / n);
Console.WriteLine("{0}", (double)c / n);
Console.ReadKey();
}
In my case nothing worked above.
what I want to do is divide 278 by 575 and multiply by 100 to find percentage.
double p = (double)((PeopleCount * 1.0 / AllPeopleCount * 1.0) * 100.0);
%: 48,3478260869565 --> 278 / 575 ---> 0
%: 51,6521739130435 --> 297 / 575 ---> 0
if I multiply the PeopleCount by 1.0 it makes it decimal and division will be 48.34...
also multiply by 100.0 not 100.
If you are looking for 0 < a < 1 answer, int / int will not suffice. int / int does integer division. Try casting one of the int's to a double inside the operation.
The answer marked as such is very nearly there, but I think it is worth adding that there is a difference between using double and decimal.
I would not do a better job explaining the concepts than Wikipedia, so I will just provide the pointers:
floating-point arithmetic
decimal data type
In financial systems, it is often a requirement that we can guarantee a certain number of (base-10) decimal places accuracy. This is generally impossible if the input/source data is in base-10 but we perform the arithmetic in base-2 (because the number of decimal places required for the decimal expansion of a number depends on the base; one third takes infinitely many decimal places to express in base-10 as 0.333333..., but it takes only one decimal in base-3: 0.1).
Floating-point numbers are faster to work with (in terms of CPU time; programming-wise they are equally simple) and preferred whenever you want to minimize rounding error (as in scientific applications).

Exponents in C#

int trail = 14;
double mean = 14.00000587000000;
double sd = 4.47307944700000;
double zscore = double.MinValue;
zscore = (trail - mean) / sd; //zscore at this point is exponent value -1.3122950464645662E-06
zscore = Math.Round(zscore, 14); //-1.31229505E-06
Math.Round() also keeps the exponent value. should zscore.ToString("F14") be used instead of Math.Round() function to convert it to non-exponent value? Please explain.
These are completely independant concerns.
Math.Round will actually return a new value, rounded to the specified decimal (ar at least, as near as one can do with floating point).
You can reuse this result value anywhere, and show it with 16 decimals precision if you want, but it's not supposed to be the same as the original one.
The fact that it is displayed with exponent notation or not has nothing to do with Round.
When you use ToString("F14") on a number, this is a display specification only, and does not modify the underlying value in any way. The underlying value might be a number that would or would not display as exponential notation otherwise, and may or may actually have 14 significant digits.
It simply forces the number to be displayed as a full decimal without exponent notation, with the number of digits specified. So it seems to be what you actually want.
Examples :
(executable online here : http://rextester.com/PZXDES55622)
double num = 0.00000123456789;
Console.WriteLine("original :");
Console.WriteLine(num.ToString());
Console.WriteLine(num.ToString("F6"));
Console.WriteLine(num.ToString("F10"));
Console.WriteLine(num.ToString("F14"));
Console.WriteLine("rounded to 6");
double rounded6 = Math.Round(num, 6);
Console.WriteLine(rounded6.ToString());
Console.WriteLine(rounded6.ToString("F6"));
Console.WriteLine(rounded6.ToString("F10"));
Console.WriteLine(rounded6.ToString("F14"));
Console.WriteLine("rounded to 10");
double rounded10 = Math.Round(num, 10);
Console.WriteLine(rounded10.ToString());
Console.WriteLine(rounded10.ToString("F6"));
Console.WriteLine(rounded10.ToString("F10"));
Console.WriteLine(rounded10.ToString("F14"));
will output:
original :
1,23456789E-06
0,000001
0,0000012346
0,00000123456789
rounded to 6
1E-06
0,000001
0,0000010000
0,00000100000000
rounded to 10
1,2346E-06
0,000001
0,0000012346
0,00000123460000

C# Math.Round very long double - not working

here is what I'm trying to do:
double result = Math.Pow((1 + 8), 60) - 1;
And the result variable is:
1.7970102999144311E+57 double
And trying to:
Math.Round(result, 5);
Returns same : 1.7970102999144311E+57 double
I'd like to round it to 1.79701 for example
Any solutions ?
You're misunderstanding what you're seeing.
1.7970102999144311E+57
Is scientific notation for
1797010299914431100000... (with 41 trailing zeros).
It is a whole number, thus rounding it to 5 decimal places will correctly return the same value.
What you want to do is format the output of the number
String.Format(CultureInfo.InvariantCulture, "{0:0.#####E+0}", result);
Which returns 1.79701E+57. Note that this is a very different number from 1.79701
The problem you're having is that Math.Round rounds things to the right of the decimal point. For example if you're dealing with currency and you perform an operation that leaves you with $1.5234524, you would use:
Math.Round(1.5234524,2);
// output 1.52
The number you're dealing with is actually scientific notation for a very large number with nothing to the right of the decimal point. This is why the result of Math.Round is the same as the input.
The earlier comments and answers are correct. But to get what you are trying to achieve you can use the following:
double result = Math.Pow((1 + 8), 60) - 1;
string s = String.Format("{0:E5}", result);
double d = Double.Parse(s);

Increasing the value by 1 if it has decimal place?

My scenario is that if
47/15= 3.13333
i want to convert it into 4, if the result has decimal i want to increase the result by 1, right now i am doing this like
float res = ((float)(62-15) / 15);
if (res.ToString().Contains("."))
{
string digit=res.ToString().Substring(0, res.ToString().IndexOf('.'));
int incrementDigit=Convert.ToInt16(k) + 1;
}
I want to know is there any shortcut way or built in function in c# so that i can do this fast without implementing string functions.
Thanks a lot.
Do you mean you want to perform integer division, but always rounding up? I suspect you want:
public static int DivideByFifteenRoundingUp(int value) {
return (value + 14) / 15;
}
This avoids using floating point arithmetic at all - it just allows any value which isn't an exact multiple of 15 to be rounded up, due to the way that integer arithmetic truncates towards zero.
Note that this does not work for negative input - for example, if you passed in -15 this would return 0. you could fix this with:
public static int DivideByFifteenRoundingUp(int value) {
return value < 0 ? value / 15 : (value + 14) / 15;
}
Use Math.Ceiling Quoting MSDN:
Returns the smallest integral value that is greater than or equal to
the specified decimal number.
You are looking for Math.Ceiling().
Convert the value you have to a Decimal or Double and the result of that method is what you need. Like:
double number = ((double)(62-15) / (double)15);
double result = Math.Ceiling(number);
Note the fact that I cast 15 to a double, so I avoid integer division. That is most likely not what you want here.
Another way of doing what you ask is to add 0.5 to every number, then floor it (truncate the decimal places). I'm afraid I don't have access to a C# compiler right now to confirm the exact function calls!
NB: But as others have confirmed, I would think the Math.Ceiling function best communicates to others what you intend.
Something like:
float res = ((float)(62-15) / 15);
int incrementDigit = (int)Math.Ceiling(res);
or
int incrementDigit = (int)(res + 0.5f);

How can I round numbers up instead of down?

I'm performing some calculations and inserting the result into a database.
My problem is, that the answers I'm getting seem to be rounding down rather than up. This might not seem important but over the course of a lot of sales, the cents start adding up!!
Decimal pubCut = rrp * (percentageCutD / 100);
Decimal retCut = rrp * retailerCut;
Decimal edcut = rrp * edpercentage;
I'll be honest, I'm rubbish with figures and the whole Maths function was something I tried to avoid in college. Can anyone tell me how I can get these figures to round up as opposed to down?
Use Math.Ceiling() method.
double[] values = {7.03, 7.64, 0.12, -0.12, -7.1, -7.6};
Console.WriteLine(" Value Ceiling Floor\n");
foreach (double value in values)
Console.WriteLine("{0,7} {1,16} {2,14}",
value, Math.Ceiling(value), Math.Floor(value));
// The example displays the following output to the console:
// Value Ceiling Floor
//
// 7.03 8 7
// 7.64 8 7
// 0.12 1 0
// -0.12 0 -1
// -7.1 -7 -8
// -7.6 -7 -8
Your problem is this
(percentageCutD / 100)
Since 100 is an int, it will perform integer division, so that 150/100 becomes 1. You can fix this by maksing sure that 100 is a decimal since you want a decimal as result in the end. Change your code to.
(percentageCutD / 100D)
However, if you always want to round values even like 1.1 up to 2, then you will have to use Math.Ceiling to accomplish this. If you for some reason want to avoid the Math class (I can't see why you want to do it, you can add 1 to the result and cast it to an int to effectively round up to the nearest integer.
.Net's Math.Round function uses something commonly referred to as banker's rounding which works by rounding .5 to the nearest even integer, ie 22.5 = 22 and 23.5 = 24. This gives a more even distribution when rounding.
It's also worth noting the SQL server doesn't use bankers rounding
Your incoming percentages probably don't add to 100 %. Compute one of your fractions by substracting the sum of the other fractions from the total.
var v = 100D;
var p1 = 33D/100;
var p2 = 33D/100;
var p3 = 33D/100;
var v1 = p1*v;
var v2 = p2*v;
var v3 = p3*v;
var sum = v1 + v2 + v3;
Unfortunately sum is 99 and not 100.
You can compute v3 like this instead:
var v3 = v - (v1 + v2);
Or better fix the rounding error in the incoming percentages:

Categories