Calculation of database cells values - c#

I have a database with a table, containing two integer fields.
When I try to get a percentage (fieldA / (fieldA+fieldB)), the value is 0.
double percentage = fieldA+fieldB // WORKS; 5+5=10
double percentage = fieldA / (fieldA+fieldB) // DOES NOT WORK; 5+5=0
So what's the problem here? Thanks..

When you do fieldA / (fieldA+fieldB) you get 5/10, which as an integer is truncated to 0, you have to do double division if you want 0.5 as a result.
i.e. something like this:
double percentage = (double)fieldA/(fieldA+fieldB)

I do assume fieldA and fieldB are integers? If yes, you should be aware that dividing two integers results in an integer, too, no matter what is on the left side of the equation.
So dividing fieldA by (fieldA+fieldB) results in a value < 1 which results in zero. See Integer Division on Wikipedia.
To correct the issue, simply cast at least one operand to a floating point type like e.g.:
double percentage = fieldA/(double)(fieldA+fieldB)

Since fieldA and fieldB are integers, the expression fieldA / (fieldA+fieldB)is of the form int / int which means you will use integer division, in this case - 5/10 = 0, as integer division solves x = am + b, and in this case 5 = a*10 + b which means a = 0, b = 5
You can do however:
double percentage = (double)fieldA / (fieldA+fieldB);

You may need to cast the fields as doubles before applying the operation

try this : double percentage = (double)fieldA/(double)(fieldA+fieldB)

if both fields are integer, then the addition of the two integer results also integer.
Try this
float result = (float)((A*100)/(B+A));
Answer: result = 50.0

Related

C#. Strange behavior of double

Here is the code which made me post this question.
// int integer;
// int fraction;
// double arg = 110.1;
this.integer = (int)(arg);
this.fraction = (int)((arg - this.integer) * 100);
The variable integer is getting 110. That's OK.
The variable fraction is getting 9, however I am expecting 10.
What is wrong?
Update
It seems I have discovered that the source of the problem is subtraction
arg - this.integer
Its result is 0.099999999999994316.
Now I am wondering how I should correctly subtract so that the result was 0.1.
You have this:
fraction = (int)((110.1 - 110) * 100);
The inner part ((110.1 - 110) * 100), will be 9.999999
When you cast it to int, it will be round off to 9
This is because of "floating point" (see here) limitations:
Computers always need some way of representing data, and ultimately
those representations will always boil down to binary (0s and 1s).
Integers are easy to represent, but non-integers are a bit more
tricky. Consider the following var:
double x = 0.1d;
The variable x will actually store the closest available double to
that value. When you understand this, it becomes obvious why some
calculations seem to be "wrong".
If you were asked to add a third to a third, but could only use 3
decimal places, you'd get the "wrong" answer: the closest you could
get to a third is 0.333, and adding two of those together gives 0.666,
rather than 0.667 (which is closer to the exact value of two thirds).
Update:
In financial applications or where the numbers are so important to be exact, you can use decimal data type:
(int)((110.1m - 110) * 100) //will be 10 (m is decimal symbol)
or:
decimal arg = 110.1m;
int integer = (int)(arg); //110
decimal fraction = (int)((arg - integer) * 100); //will be 10
It is because you are using double, precision gets rounded, if you want it to be 10 use decimal type:
check the following:
int integer;
int fraction;
decimal arg = 110.1M;
integer = (int)(arg);
decimal diff = arg - integer;
decimal multiply = diff * 100;
fraction = (int)multiply;//output will be 10 as you expect

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

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;

C# double, decimal problems

Why does this calcuation: double number = (13 /(13+12+13))
equals 0?
It should be around 0.34, I think!
Thanks!
Because you are dividing an int with an int. You should be doing
double number = (13.0 /(13.0+12.0+13.0));
That are integers. So it does integer division. And thus truncates to the next lower(closer to 0) integer.
Add a .0 to a number like 13.0 to make it a double.
Because you're using all INT in your formula - it will be treated as INT for the result too.
Try this instead:
var result = 13.0 / (13.0 + 12.0 + 13.0)
and your result will be:
0.34210526315789475
Try adding a .0:
(13.0 /(13+12+13))
Otherwise you're dealing with integers.
Another option is to cast one of the arguments explicitly to double and thus forcing the runtime to perform double division. e.g. :
double result = ((double)13 / (13 + 12 + 13));
Adding a ".0" will help:
double number = (13.0 /(13.0+12.0+13.0));

Possible Loss of Fraction

Forgive me if this is a naïve question, however I am at a loss today.
I have a simple division calculation such as follows:
double returnValue = (myObject.Value / 10);
Value is an int in the object.
I am getting a message that says Possible Loss of Fraction. However, when I change the double to an int, the message goes away.
Any thoughts on why this would happen?
When you divide two int's into a floating point value the fraction portion is lost. If you cast one of the items to a float, you won't get this error.
So for example turn 10 into a 10.0
double returnValue = (myObject.Value / 10.0);
You're doing integer division if myObject.Value is an int, since both sides of the / are of integer type.
To do floating-point division, one of the numbers in the expression must be of floating-point type. That would be true if myObject.Value were a double, or any of the following:
double returnValue = myObject.Value / 10.0;
double returnValue = myObject.Value / 10d; //"d" is the double suffix
double returnValue = (double)myObject.Value / 10;
double returnValue = myObject.Value / (double)10;
An integer divided by an integer will return your an integer. Cast either Value to a double or divide by 10.0.
Assuming that myObject.Value is an int, the equation myObject.Value / 10 will be an integer division which will then be cast to a double.
That means that myObject.Value being 12 will result in returnValue becoming 1, not 1.2.
You need to cast the value(s) first:
double returnValue = (double)(myObject.Value) / 10.0;
This would result in the correct value 1.2, at least as correct as doubles will allow given their limitations but that's discussed elsewhere on SO, almost endlessly :-).
I think since myObject is an int, you should
double returnValue=(myObject.Value/10.0);

Categories

Resources