Arithmetic Operation: Int to Double - c#

I am using 2 textboxes and a button in my Windows application.
textBox1 is for user input
textBox2 displays the result of the arithmetic operation.
When the user clicks a button, the following operation should be performed:
1000 * textbox1.text / 60
For this i used
private void button1_Click(object sender, EventArgs e)
{
int Result = 1000 * Convert.ToInt32(textBox1.Text) / 60;
textBox2.Text = Result.ToString();
}
The value I'm getting, however, is an integer, even when I'd expect it to be a double.
How can I fix this?

The rule is:
When one integer is divided by another, the arithmetic is performed as
integer arithmetic. If you want it to be performed as float, double or
decimal arithmetic, you need to cast one of the values appropriately.
So all of these will work:
double Result = 1000 * Convert.ToDouble(textBox1.Text) / 60;
double Result = 1000 * Convert.ToInt32(textBox1.Text) / (double)60;
double Result = 1000 * Convert.ToInt32(textBox1.Text) / 60.0;
From MSDN about integer division:
The result is the integer quotient of number1 divided by number2. The
integer quotient discards any remainder and retains only the integer
portion.

You should have at least 1 double on the right side
double Result = 1000 * Convert.ToInt32(textBox1.Text) / 60.0;
Additional note: in order to have a double as a result of an operation like this one, you must give it at least one double, else the right part (1000 * Convert.ToInt32(textBox1.Text) / 60) will just be an integer, THEN converted to a double by the implicit cast from the left part (double Result =).

You're forcing the result to be an integer all the way :
int Result = 1000 * Convert.ToInt32(textBox1.Text) / 60;
You should force Result to be a Double, and force both operands to be doubles :
double Result = 1000 * Convert.ToDouble(textBox1.Text) / 60d;
(60d stands for (double) 60 - I prefer using type suffixes instead of casts, but it is the same)

Related

Divide by 0 error C# [duplicate]

This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
18 / 58 is an integer division, which results in 0.
If you want decimal division, you need to use decimal literals:
decimal share = (18m / 58m) * 100m;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;

Division by 0.9 c# always returns 0

I'm trying to do a simple picee of maths where I work out if a value is between two values and if so, it does, it should do a simple division. However sometimes the value divided by are like 0.9, 0.6 etc and that always returns 0.
in this example,
int m_LocationSqrMtr = 4339;
float m_DefaultPricing = Convert.ToSingle(DefaultPricing);
float m_manDays;
if (m_LocationCosts > 450 && m_LocationCosts < 700)
{
m_DefaultPricing = 700 / m_LocationSqrMtr;
}
My guess is that the type of m_LocationSqrMtr is int, in which case this expression:
700 / m_LocationSqrMtr
... will be computed using integer arithmetic, and the result converted to float. I suspect you want:
if (m_LocationCosts > 450 && m_LocationCosts < 700)
{
m_DefaultPricing = 700f / m_LocationSqrMtr;
}
The f suffix on the literal means that it's a float literal, so first m_LocationSqrMtr will be promoted to float, and then the division performed using float arithmetic.
However, if this is meant to be representing currency values, you should consider using decimal instead of float - and then probably rounding the value to 2 decimal places. If you do all your currency arithmetic in decimal, you're less likely to run into unexpected results...
You have:
int m_LocationSqrMtr = 4339;
[...]
m_DefaultPricing = 700 / m_LocationSqrMtr;
That is, 700 / 4339, which is (integer) / (integer), the result of which is an integer.
I know you were expecting an answer of 0.16132....
But in integer terms, that value is ZERO.
If the type of m_LocationSqrMtr is int, as in a 32-bit whole number, then the expression
700 / m_LocationSqrMtr
is one integer divided by another integer, and it's type is integer. Only after this integer is produced is the result assigned to the float m_DefaultPricing, so basically your code is equivalent to:
int temp = 700 / m_LocationSqrMtr;
m_DefaultPricing = (float) temp;
If you want to force floating point arithmetic, at least one of the operands needs to be a floating point number. There are a number of ways that this can be done:
m_DefaultPricing = 700.0 / m_LocationSqrMtr; //explicit decimal point
m_DefaultPricing = 700f / m_LocationSqrMtr; //explicit float specification
m_DefaultPricing = (float)700 / m_LocationSqrMtr; //casting one operand
m_DefaultPricing = 700f / (float)m_LocationSqrMtr; //into a float
There are already a number of good practical answers so on a more conceptual level:
In C# if both sides of the operator are an integer the result is also an integer and any decimal digits are truncated. In general, for math, the language will produce a result of the same type as the input with the most precise type. The type of variable you store the result in will have no effect on the result only the types of the inputs.
By forcing one input to be decimal or float you force the output to be that as well. In practice you can either do this by declaring your one of your input variables as a decimal or float (depending on which you use, in your case you would change the type of m_LocationSqrMtr) or if you have a constant input (as you do) you can force it to be decimal/float/double as follows:
var a = 10f // float
var b = 10d // double
var c = 10m // decimal
var d = 10.0 // double I believe

Multiplication on floating numbers returns unexpected result

int countBouncy=5;
int count=999899;
double percent = (double)(countBouncy / count) * 100.0;
The result of that phrase is unexpected, I get zero.
Why won't it work?
You are doing an integer division on (countBouncy / count). Change your code to
double percent = ((double)countBouncy / count) * 100.0;
That way, countBouncy is converted to double explicitly and count is converted to double implicitly by the c# compiler to make it compatible to the (now double) countBouncy.
Otherwise (countBouncy / count) is calculated as (5 / 999899) --> 0 since both are integers.
How does integer division work? Let's take an example:
7 / 2 = 3
Integer division drops the decimal part that a real division would yield. The result is truncated towards zero. You can get the remainder of this division by using the modulo operator
7 % 2 = 1
and perform the backward calculation like this
2 * (7 / 2) + 7 % 2 = 7
You can enter this in the immediate window of Visual Studio to test it:
?2 * (7 / 2) + 7 % 2<enter>
7
Because your division is integer division, which results in 0, which you then cast into a double.
Your current code is effectively the same as:
int temp = countBouncy / count; // == 0
double percent = (double)temp * 100.0;
Do you cast on one of the items first:
double percent = ((double)countBouncy / count) * 100.0;
That will cause your division to be done in double precision up front.
When you divide an int by an int, the result is always an int, so it's going to round down to the nearest integer (zero). Try this instead:
((double)countBouncy / count) * 100.0;
Your numerator and denominator are both ints. Hence, the resulting quotient is an int which C# calculates by rounding down to 0. Plus, you are trying to assign a double type to an int type. In order to achieve your desired result, do:
double percent = ((double) countBouncy / count) * 100.0;

Division returns zero

This simple calculation is returning zero, I can't figure it out:
decimal share = (18 / 58) * 100;
You are working with integers here. Try using decimals for all the numbers in your calculation.
decimal share = (18m / 58m) * 100m;
18 / 58 is an integer division, which results in 0.
If you want decimal division, you need to use decimal literals:
decimal share = (18m / 58m) * 100m;
Since some people are linking to this from pretty much any thread where the calculation result is a 0, I am adding this as a solution as not all the other answers apply to case scenarios.
The concept of needing to do calculations on various types in order to obtain that type as a result applies, however above only shows 'decimal' and uses it's short form such as 18m as one of the variables to be calculated.
// declare and define initial variables.
int x = 0;
int y = 100;
// set the value of 'x'
x = 44;
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0.
Console.WriteLine( (x / y).ToString() );
// Results in 0 as the whole number 44 over the whole number 100 is a
// fraction less than 1, and thus is 0. The conversion to double happens
// after the calculation has been completed, so technically this results
// in 0.0
Console.WriteLine( ((double)(x / y)).ToString() );
// Results in 0.44 as the variables are cast prior to calculating
// into double which allows for fractions less than 1.
Console.WriteLine( ((double)x / (double)y).ToString() );
Because the numbers are integers and you perform integer division.
18 / 58 is 0 in integer division.
Whenever I encounter such situations, I just upcast the numerator.
double x = 12.0 / 23409;
decimal y = 12m / 24309;
Console.WriteLine($"x = {x} y = {y}");
double res= (firstIntVar * 100f / secondIntVar) / 100f;
when dividing numbers I use double or decimal , else I am getting 0 , with this code even if firstIntVar && secondIntVar are int it will return the expected answer
decimal share = (18 * 100)/58;
Solved: working perfectly with me
int a = 375;
int b = 699;
decimal ab = (decimal)a / b * 100;

Strange problem with a C# function I am trying to write

I have this function I am writing.
const int ProgressBarLength = 230;
foreach (TransactionDetail item in list)
{
var itemProgress =
((ProgressBarLength/item.PurchasesRequired) *
Convert.ToInt32(item.TransactionAmount));
item.ProgressBar = itemProgress > ProgressBarLength ? ProgressBarLength : itemProgress;
}
Now I have 2 TransactionDetails in my loop.
If item.PurchasesRequired = 500 and TransactionAmount = 199.0 the resulting value is 0. However, if item.PurchasesRequired = 5 and TransactionAmount = 94.0 it returns a valid result.
What am I doing wrong?
Is item.PurchasesRequired an int?
If so, your problem is integer division.
ProgressBarLength is an int, so 230/500 = 0.
Use float, double, or decimal (either in a cast or for your ProgressBarLength) to maintain your desired level of precision.
I'm guessing you should do a cast to double somewhere to have more precision in your divisions. When dividing an int by an int, you won't get a double as result.
Try the following:
double itemProgress = ( ((double)ProgressBarLength / item.PurchasesRequired )
* Convert.ToInt32( item.TransactionAmount ) );
It looks like you're performing integer division.
230 / 500 is zero in integer division, whereas 230 / 5 is 46.
You can force floating-point division by casting PurchasesRequired to a double. 230 / 500 is 0.46 in floating-point division, as you'd expect.
const int ProgressBarLength = 230;
foreach (TransactionDetail item in list)
{
var itemProgress = ((ProgressBarLength / (double)item.PurchasesRequired)
* Convert.ToInt32(item.TransactionAmount));
item.ProgressBar = Math.Min((int)itemProgress, ProgressBarLength);
}
I'm guessing TransactionDetail.PurchaseRequired is a field or property of type int.
ProgressBarLength/item.PurchasesRequired divides an in by an int which results in an int, not a float. in your first example, 230 / 500 does integer division and the result is, of course, 0.
You can either calculate the expression as a double, or do the multiplication first so that you don't lose relevant precision from the integer division.
var itemProgress = (double) ProgressBarLength / item.PurchasesRequired * item.TransactionAmount;
or
var itemProgress = ProgressBarLength * (int) item.TransactionAmount / item.PurchasesRequired));

Categories

Resources