How to round up result of dividing - c#

finalResult = Math.Ceiling(result = (x - y) / (z - 1));
I am trying to get whole rounded number. finalResult and result are double. Others are int. And well... not working.
I would appreciate some help. Thank you.

In order to get the result of this operation as double you have to make at least one operand double (see https://msdn.microsoft.com/en-us/library/3t4w2bkb.aspx). Try adding 'd' to literal:
finalResult = Math.Ceiling(result = (x - y) / (z - 1d));
By doing this little trick you ensure that '1' will be treated as double, not as int, so the whole operation outcome will be a double.
Note: Unless you want to round this value up, you should change the rounding method to Math.Round().
Note 2: Make sure to prevent division by 0 by checking if(z != 0).

Since x, y and z are all int, then the division will be done as integer and will be truncated.
To avoid that, simply cast like so:
finalResult = Math.Ceiling(result = (x - y) / (double)(z - 1));
(I'm assuming here you want to round up, so if the result of the division was, say, 1.00001, you'd want the rounded result to be 2.0.)

You need a type casting to get Math.Ceiling to work.
Decimal finalResult = Math.Ceiling(((Decimal)(x - y)) / (z - 1));

Related

Convert int to 0-1 float

I wonder why my next statement always returns 1, and how I can fix it. I accounted for integer division by casting the first element in the division to float. Apart from that I'm not getting much further.
int value = any int;
float test = (float)value / int.MaxValue / 2 + 1;
By the way my intention is to make this convert ANY integer to a 0-1 float
To rescale a number in the range s..e to 0..1, you do (value-s)/(e-s).
So in this case:
double d = ((double)value - int.MinValue) / ((double)int.MaxValue - int.MinValue);
float test = (float)d;
It doesn't always return zero. For example, this code:
int value = 12345678;
float test = (float)value / int.MaxValue / 2 + 1;
Console.WriteLine(test);
Prints 1.002874
The problem is that floats are not very precise, so for small values of value, the result will be 0 to the number of digits of precision that floats can handle.
For example, value == 2300 will print 0, but value == 2400 will print 1.000001.
If you use double you get better results:
int value = 1;
double test = (double)value / int.MaxValue / 2 + 1;
Console.WriteLine(test);
Prints 1.00000000023283
Avoid implicit type conversions. Use all elements in your expression of type double, if that is the type you want. Convert the int.MaxValue and the 2 to double before using them in the division, so that no implicit type conversions are involved.
Also, you might want to parenthesize your expression to make it more readable. As it is, it is error prone.
Finally, if your expression is too complex and you don't know what's going on, split it into simpler expressions, all of them of type double.
P.S.: By the way, trying to get precise results and using float instead of double is not a very wise thing to do. Use float for precise floating point calculations.

Simple calculator always return 0

In my C# application I want to implement a simple calculation. I got this code:
private void button1_Click(object sender, EventArgs e)
{
int percentField;
int priceField;
int result;
percentField = int.Parse(txtPercentNew.Text);
priceField = int.Parse(txtPriceNew.Text);
result = priceField / 100 * percentField;
MessageBox.Show(result.ToString());
}
But the problem is the MessageBox displays me 0. I can't figure out why.
Can someone please give me a hint what I am doing wrong?
Your variables are integers, which means that / performs integer division. Unless priceField is at least equal to 100 you will always get 0 as the result.
You can correct the problem by casting priceField to a floating point type before dividing:
(double)priceField / 100 * percentField;
However, this will not work while result is of type int because the compiler wants to protect you from inadvertent rounding errors. So you either have to cast back to an integer (losing precision due to rounding):
result = (int)((double)priceField / 100 * percentField);
or else make result be a double as well.
You are using integers instead of floating point numbers.
As a consequence, rounding off occurs during calculation.
Use float or double instead of int.
Probably your priceField is less then 100 and since you doing integer division, it creates 0 as a result.
From / Operator (C# Reference)
When you divide two integers, the result is always an integer. For
example, the result of 7 / 3 is 2. To determine the remainder of 7 /
3, use the remainder operator (%). To obtain a quotient as a rational
number or fraction, give the dividend or divisor type float or type
double. You can assign the type implicitly if you express the dividend
or divisor as a decimal by putting a digit to the right side of the
decimal point, as the following example shows.
Just cast one of your variables to floating point type like;
result = priceField / 100d * percentField;
or
result = (double)priceField / 100 * percentField;
You are working with only integers, try
double result;
result = priceField / (double)100 * percentField;
In your code, you are dividing by 100. Which means every int you are going to divide less than 100 will result in a value between [0 - 1]. When implicitly casting to an int, the result will be floored. Therefor, a 0.1 will become 0 - a 0.9 will become 0 - ...
try cast to double, because you're working with integers it results in 0.
example here
The problem is you're using int for each value.
Change result to a double and try this:
result = (double)priceField / 100 * percentField;
It should work; however, if you want to do this properly I recommend you read about MidpointRounding.

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);

C# simple divide problem

I have this:
double result = 60 / 23;
In my program, the result is 2, but correct is 2,608695652173913. Where is problem?
60 and 23 are integer literals so you are doing integer division and then assigning to a double. The result of the integer division is 2.
Try
double result = 60.0 / 23.0;
Or equivalently
double result = 60d / 23d;
Where the d suffix informs the complier that you meant to write a double literal.
You can use any of the following all will give 2.60869565217391:
double result = 60 / 23d;
double result = 60d / 23;
double result = 60d/ 23d;
double result = 60.0 / 23.0;
But
double result = 60 / 23; //give 2
Explanation:
if any of the number is double it will give a double
EDIT:
Documentation
The evaluation of the expression is performed according to the following rules:
If one of the floating-point types is double, the expression evaluates to double (or bool in the case of relational or Boolean expressions).
If there is no double type in the expression, it evaluates to float (or bool in the case of relational or Boolean expressions).
It will work
double result = (double)60 / (double) 23;
Or equivalently
double result = (double)60 / 23;
(double) 60 / 23
Haven't used C# for a while, but you are dividing two integers, which as far as I remember makes the result an integer as well.
You can force your number literals to be doubles by adding the letter "d", likes this:
double result = 60d / 23d;
double result = 60.0 / 23.0;
It is best practice to correctly decorate numerals for their appropriate type. This avoids not only the bug you are experiencing, but makes the code more readable and maintainable.
double x = 100d;
single x = 100f;
decimal x = 100m;
convert the dividend and divisor into double values, so that result is double
double res= 60d/23d;
To add to what has been said so far... 60/23 is an operation on two constants. The compiler recognizes the result as a constant and pre-computes the answer. Since the operation is on two integers, the compiler uses an integer result The integer operation of 60/23 has a result of 2; so the compiler effective creates the following code:
double result = 2;
As has been pointed out already, you need to tell the compiler not to use integers, changing one or both of the operands to non-integer will get the compiler to use a floating-point constant.

To return a double, do I have to cast to double even if types are double in c#?

To return a double, do I have to cast to double even if types are double?
e.g.
double a = 32.34;
double b = 234.24;
double result = a - b + 1/12 + 3/12;
Do I have to cast (double) ?
No, you don't. However, your expression almost certainly doesn't do what you want it to.
The expressions 1/12 and 3/12 will be performed using integer arithmetic.
You probably want:
double result = a - b + 1/12d + 3/12d;
or
double result = a - b + 1/(double) 12 + 3/(double) 12;
Both of these will force the division to be performed using floating point arithmetic.
The problem here is that if both operands of an arithmetic operator are integers, then the operation is performed using integer arithmetic, even if it's part of a bigger expression which is of type double. Here, your expression is effectively:
double result = a - b + (1 / 12) + (3 / 12);
The addition and subtraction is okay, because the types of a and b force them to be performed using floating point arithmetic - but because division "binds more tightly" than addition and subtraction (i.e. it's like using the brackets above) only the immediate operands are considered.
Does that make sense?
EDIT: As it's so popular, it makes sense to include devinb's comment here too:
double result = a - b + 1.0/12.0 + 3.0/12.0;
It's all the same thing as far as the compiler is concerned - you just need to decide which is clearer for you:
(double) 1
1.0
1d
Nope, no casting is needed.
Of course, there's a clean way to do this without casting:
double result = a - b + 1.0/12 + 3.0/12;
That really depends on what you're asking about casting. Here are two different cases:
double a = 32.34;
double b = 234.24;
double result1 = a - b + 1/12 + 3/12;
double result2 = a - b + (double)1/12 + (double)3/12;
Console.WriteLine(result1); // Result: -201.9
Console.WriteLine(result2); // Result: -201.566666666667
Either way you're not going to get any complaints about assigning the value to result, but in the first case the division at the end is done using integers which resolve to 0.
Hmm - The way that I've done this for the integer division issue is to do something like:
double result = a - b + 1/12.0 + 3/12.0
Aside from those though, no casting would be needed.
You should not need to, although it's hard to tell from your question where the cast would be.
When doing math, C# will return the result as the type of whichever argument has the larger type.
As I recall, the order goes something like this (from largest to smallest):
decimal
double
float
long / int64
int / int32
short / int16
byte
Of course, this is skipping the unsigned versions of each of these.
In general no casting is needed, but in your example, the 1/12 and 3/12 are integer division, resulting in 0 for each expression. You would need to cast one of the numerator or denominator to double.
Casting is used to indicate whenever you want to change one datatype to another type. This is because changing the type usually involves a possible loss of data.
e.g.
double a = 8.49374;
//casting is needed because the datatypes are different.
// a_int will end up with the value is 8, because the precision is lost.
int a_int = (int) a;
double b = (double) a_int;
In that example 'b' will end up with the value of "8.00000..." this is because a_int does not contain ANY decimal information, and so b only has the integer related information at its disposal.

Categories