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;
Related
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
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
I am writing a program that finds percentile. According to eHow:
Start to calculate the percentile of your test score (as an example we’ll stick with your score of 87). The formula to use is L/N(100) = P where L is the number of tests with scores less than 87, N is the total number of test scores (here 150) and P is the percentile. Count up the total number of test scores that are less than 87. We’ll assume the number is 113. This gives us L = 113 and N = 150.
And so, according to the instructions, I wrote:
string[] n = Interaction.InputBox("Enter the data set. The numbers do not have to be sorted.").Split(',');
List<Single> x = new List<Single> { };
foreach (string i in n)
{
x.Add(Single.Parse(i));
}
x.Sort();
List<double> lowerThan = new List<double> { };
Single score = Single.Parse(Interaction.InputBox("Enter the number."));
uint length = (uint)x.Count;
foreach (Single index in x)
{
if (index > score)
{
lowerThan.Add(index);
}
}
uint lowerThanCount = (uint)lowerThan.Count();
double percentile = lowerThanCount / length * 100;
MessageBox.Show("" + percentile);
Yet the program always returns 0 as the percentile! What errors have I made?
Your calculation
double percentile = lowerThanCount / length * 100;
is all done in integers, since the right hand side consist of all integers. Atleast one of the operand should be of floating point type. So
double percentile = (float) lowerThanCount / length * 100;
This is effectively a rounding problem, lowerThanCount / length are both unit therefore don't support decimal places so any natural percentage calculation (e.g. 0.2/0.5) would result in 0.
For example, If we were to assume lowerThanCount = 10 and length = 20, the sum would look something like
double result = (10 / 20) * 100
Therefore results in
(10 / 20) = 0.5 * 100
As 0.5 cannot be represented as an integer the floating point is truncated which leaves you with 0, so the final calculation eventually becomes
0 * 100 = 0;
You can fix this by forcing the calculation to work with a floating point type instead e.g.
double percentile = (double)lowerThanCount / length * 100
In terms of readability, it probably makes better sense to go with the cast in the calculation given lowerThanCount & length won't ever naturally be floating point numbers.
Also, your code could be simplified a lot using LINQ
string[] n = Interaction.InputBox("Enter the data set. The numbers do not have to be sorted.")
.Split(',');
IList<Single> x = n.Select(n => Single.Parse(n))
.OrderBy(x => x);
Single score = Single.Parse(Interaction.InputBox("Enter the number."));
IList<Single> lowerThan = x.Where(s => s < score);
Single percentile = (Single)lowerThan.Count / x.Count;
MessageBox.Show(percentile.ToString("%"));
The problem is in the types that you used for your variables: in this expression
double percentile = lowerThanCount / length * 100;
// ^^^^^^^^^^^^^^^^^^^^^^^
// | | |
// This is integer division; since length > lowerThanCount, its result is zero
the division is done on integers, so the result is going to be zero.
Change the type of lowerThanCount to double to fix this problem:
double lowerThanCount = (double)lowerThan.Count();
You are using integer division instead of floating point division. Cast length/lowerThanCount to a float before dividing.
Besides the percentile calculation (should be with floats), I think your count is off here:
foreach (Single index in x)
{
if (index > score)
{
lowerThan.Add(index);
}
}
You go through indexes and if they are larger than score, you put them into lowerThan
Just a logical mistake?
EDIT: for the percentile problem, here is my fix:
double percentile = ((double)lowerThanCount / (double)length) * 100.0;
You might not need all the (double)'s there, but just to be safe...
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;
How can I round values to nearest integer?
For example:
1.1 => 1
1.5 => 2
1.9 => 2
"Math.Ceiling()" is not helping me. Any ideas?
See the official documentation for more. For example:
Basically you give the Math.Round method three parameters.
The value you want to round.
The number of decimals you want to keep after the value.
An optional parameter you can invoke to use AwayFromZero rounding. (ignored unless rounding is ambiguous, e.g. 1.5)
Sample code:
var roundedA = Math.Round(1.1, 0); // Output: 1
var roundedB = Math.Round(1.5, 0, MidpointRounding.AwayFromZero); // Output: 2
var roundedC = Math.Round(1.9, 0); // Output: 2
var roundedD = Math.Round(2.5, 0); // Output: 2
var roundedE = Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // Output: 3
var roundedF = Math.Round(3.49, 0, MidpointRounding.AwayFromZero); // Output: 3
Live Demo
You need MidpointRounding.AwayFromZero if you want a .5 value to be rounded up. Unfortunately this isn't the default behavior for Math.Round(). If using MidpointRounding.ToEven (the default) the value is rounded to the nearest even number (1.5 is rounded to 2, but 2.5 is also rounded to 2).
Math.Ceiling
always rounds up (towards the ceiling)
Math.Floor
always rounds down (towards to floor)
what you are after is simply
Math.Round
which rounds as per this post
You need Math.Round, not Math.Ceiling. Ceiling always "rounds" up, while Round rounds up or down depending on the value after the decimal point.
there's this manual, and kinda cute way too:
double d1 = 1.1;
double d2 = 1.5;
double d3 = 1.9;
int i1 = (int)(d1 + 0.5);
int i2 = (int)(d2 + 0.5);
int i3 = (int)(d3 + 0.5);
simply add 0.5 to any number, and cast it to int (or floor it) and it will be mathematically correctly rounded :D
You can use Math.Round as others have suggested (recommended), or you could add 0.5 and cast to an int (which will drop the decimal part).
double value = 1.1;
int roundedValue = (int)(value + 0.5); // equals 1
double value2 = 1.5;
int roundedValue2 = (int)(value2 + 0.5); // equals 2
Just a reminder. Beware for double.
Math.Round(0.3 / 0.2 ) result in 1, because in double 0.3 / 0.2 = 1.49999999
Math.Round( 1.5 ) = 2
You have the Math.Round function that does exactly what you want.
Math.Round(1.1) results with 1
Math.Round(1.8) will result with 2.... and so one.
this will round up to the nearest 5 or not change if it already is divisible by 5
public static double R(double x)
{
// markup to nearest 5
return (((int)(x / 5)) * 5) + ((x % 5) > 0 ? 5 : 0);
}
I was looking for this, but my example was to take a number, such as 4.2769 and drop it in a span as just 4.3. Not exactly the same, but if this helps:
Model.Statistics.AverageReview <= it's just a double from the model
Then:
#Model.Statistics.AverageReview.ToString("n1") <=gives me 4.3
#Model.Statistics.AverageReview.ToString("n2") <=gives me 4.28
etc...
Using Math.Round(number) rounds to the nearest whole number.
Use Math.Round:
double roundedValue = Math.Round(value, 0)
var roundedVal = Math.Round(2.5, 0);
It will give result:
var roundedVal = 3
If your working with integers rather than floating point numbers, here is the way.
#define ROUNDED_FRACTION(numr,denr) ((numr/denr)+(((numr%denr)<(denr/2))?0:1))
Here both "numr" and "denr" are unsigned integers.
Write your own round method. Something like,
function round(x)
rx = Math.ceil(x)
if (rx - x <= .000001)
return int(rx)
else
return int(x)
end
decimal RoundTotal = Total - (int)Total;
if ((double)RoundTotal <= .50)
Total = (int)Total;
else
Total = (int)Total + 1;
lblTotal.Text = Total.ToString();