Rounding double value to value ending on .0 or .5 [duplicate] - c#

This question already has answers here:
How do I round to the nearest 0.5?
(10 answers)
Closed 9 years ago.
I'm trying to round some values as the following examples and need some help to write the math calculation for it:
input -> 25 ÷ 4 = 6.25 output -> 6.5
input -> 15.5 ÷ 4 = 3.875 output -> 4.0
input -> 24.5 ÷ 4 = 6.125 output -> 6.0
any idea how to write the round math procedure please?!

This should do it.
double Divide(double numerator, double denominator)
{
double result = numerator / denominator;
//round to nearest half-integer
result = Math.Round(result * 2, MidpointRounding.AwayFromZero) / 2;
// due to peculiarities of IEEE754 floating point arithmetic
// we need to round again after dividing back by two
// to avoid a result like 1.49999999.
return Math.Round(result, 1);
}

Sorry for not aware the difficulty you encountered, so I guess maybe the different types of floating point number. Following code just does that:
public static decimal RoundedDivide<T>(T a, T b) {
var x=2*Convert.ToDecimal(a)/Convert.ToDecimal(b);
x=((int)(.5m+x)>x?1:0)+(int)x;
return x/2;
}
Two things to note:
I cannot bound a constraint of ValueType, so if you pass objects of reference types, it may throw
If you wish double as the return type, then just change it and also change .5m to .5, Convert.ToDecimal to Convert.ToDouble

Related

How can I divide an integer by an integer in C# and have a variable that has one or more decimal places? [duplicate]

This question already has answers here:
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 4 years ago.
I tried this:
var b = 100 / 95;
and b is declared as an integer. But I would like to have a number with a decimal point.
How can I do this in C#?
With two integer operands, the C# overload resolution picks a version of the division operator that does integer division.
To make C# choose real division, you need to change the type of at least one of the operands into decimal, float, or double.
You can achieve this by casting, in the general case. In your specific case, you can also just change the literals involved:
var b = 100m / 95; // decimal
var b = 100f / 95; // float
var b = 100.0 / 95; // double
Use decimal if these are exact, human-made quantities (e.g. money). Use float or double if you are dealing with approximate, physical quantities (e.g. irrational numbers, physical constants, etc).
You are doing an integer division which will ignore the fractional part of the division as it can not be stored in an int.
If you cast your variables to decimals you can store the fractional part of the division:
decimal b = (decimal)100 / (decimal)95;

Percentage calculation always returns me 0 [duplicate]

This question already has answers here:
Why do these division equations result in zero?
(10 answers)
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 4 years ago.
I'm calculating the percentage to add in a datagrid, but when I report the data it always returns me 0, what am I doing wrong?
if I have the following case: the variable quantidadeInstalada has the value of 10 and the goal has 20 the concluido would have to return me 50 but it returns me 0
private void AdicionarPessoa()
{
string Valida = ValidaPessoa();
if (Valida.Equals(""))
{
double concluido=0, falta=0;
int quantidadeInstalada = Convert.ToInt32(ttbQuantidade.Text);
int meta = Convert.ToInt32(ttbMetaPessoa.Text);
concluido = (quantidadeInstalada/meta)*100;
falta = 100-concluido;
MessageBox.Show(concluido.Text);
}
else
MessageBox.Show(Valida);
}
It's probably due to the precision of the int. Use a decimal or double instead.
When we use an integer, we lose precision.
Console.WriteLine(100 / 17); // 5
Console.WriteLine(100 / 17m); // 5.8823529411764705882352941176
Console.WriteLine(100 / 17d); // 5.88235294117647
Console.WriteLine(100 / 17f); // 5.882353
Since integers always round down, 0.99 as an integer is 0.
Note that for precision, the types of the inputs matters.
double output = input1 * input2;
For example:
double outputA = 9 / 10;
Console.WriteLine(outputA); // 0
double outputB = 9 / 10d;
Console.WriteLine(outputB); // 0.9
double outputC = 9d / 10;
Console.WriteLine(outputC); // 0.9
Here is a Fiddle.
It's because you're doing integer division. You can fix it by casting one of the variables to a double like this:
concluido = ((double)quantidadeInstalada/meta)*100;
When you're dividing int by int (as in "quantidadeInstalada/meta"), you'll get an int. Either use a fractional type (e.g. decimal, double) from the very beginning, as Shaun suggested, or (if the integral types have to stay), cast the values to a fractional type in the division expression (as itsme86 shown).

math operations always returns 0 c# [duplicate]

This question already has answers here:
C# is rounding down divisions by itself
(10 answers)
C# double not working as expected [duplicate]
(1 answer)
Closed 7 years ago.
I have c# program that calculates percentage and returns int value, but it always returns 0.
I have been writing code for 16 constitutive hours so I appreciate if you find the mistakes within it.
I debugged my code and I found that the value is being passed correctly.
private int returnFlag(int carCapacity, int subscribers)
{
int percentage = (subscribers / carCapacity)*100;
return percentage;
}
What you're seeing is the result of operating on two integers, and losing the fractional portion.
This piece of code, when using the values 5 and 14, will truncate to 0:
(subscribers / carCapacity)
You need to cast one of the operands to a double or decimal:
private int returnFlag(int carCapacity, int subscribers)
{
decimal percentage = ((decimal)subscribers / carCapacity) * 100;
return (int)percentage;
}
The issue is that since you're performing math on int (read: integer) values, any fractions or remainders get thrown out. This can be seen by changing your code to
int percentage = (subscribers / carCapacity);
percentage *= 100;
Since (subscribers / carCapacity) results in less than one, the only possible number an int can hold is 0 - and 0 * 100 is 0.
You can fix this by converting to a more precise number, such as double, before performing operations:
private int returnFlag(int carCapacity, int subscribers)
{
double percentage = ((double)subscribers / (double)carCapacity) * 100.0;
return (int)percentage;
}
Integer types (int) don't work with fractions. Change the types you are working with in your division to decimal, double, single, or float.

C# not calculating a decimal result properly [duplicate]

This question already has answers here:
Extremely basic division equation not working in c#
(3 answers)
Closed 9 years ago.
(5 / 15) * 1185 should give 395.
decimal Test = (5 / 15) * 1185;
This, however, returns 0. What am I doing wrong?
5 / 15 is an integer division and returns 0. Use 5m / 15m to force decimal.
m is the C# suffix to signify to the compiler that the number your wrote is a decimal, even if it looks like an int. You can use f for floats and d for doubles (or 5.0).
While on the topic of suffixes, there is also L for long but that wouldn't have helped your with your division because it is also an integer type.
5 // Int32
5L // Int64
5d // Double
5.0 // Double
5m // Decimal
5f // Single
You need to use floating point division, not integer division. You can get the correct result by making it a floating point number, or using m (to specify it as a decimal) behind the 15:
decimal Test = (5 / 15.0) * 1185;
or
decimal Test = (5 / 15m) * 1185;
You could also use a lambda expression :
Func<decimal, decimal, decimal, decimal> exp = (x, y, z) => (x / y) * z;
Console.WriteLine(exp(5, 15, 1185));
outputs:
394.999999
as you are expecting 395 you will need to use a Math.Round
Console.WriteLine(Math.Round(exp(5, 15, 1185), 1));
outputs: 395.0
5/15 is 0 because you are using integer division.
You can try use one of the following code:
decimal test = (5m / 15) * 1185
decimal test = ((decimal)5 / 15) * 1185
decimal test = (5.0 / 15) * 1185
The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal type does not eliminate the need for rounding but rather minimizes errors due to rounding.
Link: http://msdn.microsoft.com/en-us/library/364x0z75

C# - Decimal to integer and round depending on value

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.

Categories