Calculating Integer Percentage - c#

So I would like to calculate the percentage progress of my program as the nearest integer value
In my examples lets take
int FilesProcessed = 42;
int TotalFilesToProcess = 153;
So First I tried:
Int TotalProgress = ((FilesProcessed / TotalFilesToProcess) * 100)
This returned TotalProgress = 0
Then I tried
Int TotalProgress = (int)((FilesProcessed / TotalFilesToProcess) * 100)
This gives compiler error saying Cannot implicitly convert type decimal to int
Ive tried
Int TotalProgress = Math.Round((FilesProcessed / TotalFilesToProcess) * 100)
and get The call is ambiguous between decimal and double
and so now I've come here for help?

Cast to double first so it doesn't compute a division between integers:
int totalProgress = (int)((double)FilesProcessed / TotalFilesToProcess * 100);

int FilesProcessed = 42;
int TotalFilesToProcess = 153;
int TotalProgress = FilesProcessed * 100 / TotalFilesToProcess;
Console.WriteLine(TotalProgress);
https://dotnetfiddle.net/3GNlVd

If you want to be more accuracy, you can use:
int TotalProgress = Convert.ToInt32(Math.Round(((decimal)FilesProcessed / TotalFilesToProcess) * 100, 0));
If the numbers are greater you will have a difference. For example
int FilesProcessed = 42;
int TotalFilesToProcess = 1530;
The result with decimals will be: 2.74%, if you use the previous methods, you would find 2%, with the formula I am proposing you will obtain 3%. The last option has more accuracy.

Related

C# - Get X percent of Y dynamically

I've trying to calculate what is X% of Y, although I'm getting mixed results.
I've tried the following equations:
return (percent / i) * 100; // Gives 0 for 200.GetPercent(10)
return percent * 100 / i; // Gives 5 for 200.GetPercent(10)
For method:
public static int GetPercent(this int i, int percent)
{
return percent * 100 / i;
}
But none are giving me 20 back for 200.GetPercent(10)
I believe this is the correct equation: Y * X / 100
public static int GetPercent(this int i, int percent)
{
return (i * percent) / 100;
}
Percentages are better dealt with using a a floating point type, here is a version using double with another parameter to set precision
public static double GetPercent(this int i, double percent, int precision) =>
Math.Round(((i * percent) / 100), precision);
You can also define precision as an optional parameter, to give it a default value with int precision = n (n being an int of your choice)
public static double GetPercent(this int i, double percent, int precision = 2) =>
Math.Round(((i * percent) / 100), precision);
200.GetPercent(10, 4); //precision = 4
200.GetPercent(10); //precision defaults to = 2

showing a percentage number for two variables in c# [duplicate]

This question already has answers here:
C# is rounding down divisions by itself
(10 answers)
Closed 6 years ago.
I have two variables, I want to showing as percentage, when I calculate them with operator the result is 0 why?
please help me. Thanks
this is my source
int count = (from a in dc.jawabans
where a.q14 == "5 : Sangat Baik/ Sangat Puas"
select a).Count();
TextBox1.Text = count.ToString();
int total = (from b in dc.jawabans
where b.q14 != ""
select b).Count();
TextBox2.Text = total.ToString();
int persen = (count / total) * 100;
TextBox3.Text = persen.ToString();
This is the result
count is int, total is int too. In C# when int divided by int the result is int. The solution is to cast one variable as double.
int persen = (int)((double)count / total * 100);
Write it like this:
decimal persen = (count / (decimal)total) * 100;
After that you can round it if you want:
TextBox3.Text = Math.Round(persen, 2).ToString();
Division of 2 integers is an integer, so you should specified that one of them is decimal.
Because you dividing two integers, so the result will be integer as well. You can set count and total as double , then you will get correct result.
This is because the sum you are doing is with ints, so the value is rounded to the nearest whole number - for example if count is 20, and total is 100
int persen = (count / total) * 100;
is the same as doing
int persen = (count / total); //this = 0 as it would evaluate to 0.2 => 0
persen = persen * 100; //still 0
Whereas
int persen = ((double)count / (double)total) * 100;
//This would be 20, as count and total are both cast to a double - it also works if you only cast one of them
decimal persen = (count / (decimal)total) * 100; //count 20, total 100, so person will be 0 if it is int in your code
If you devide int by int, it will give you int not double.
So either convert count or total as decimal or double according to your requirement.

Something is wrong with the accuracy of calculation between variables

I have some problems with my code where I think the accuracy is a bit off. I'll take out the declarations of variables from my code, so the code is as small as possible:
int a = Int32.Parse(tb_weight.Text);
double b = 0;
b = (a * 1.03) / 1000;
double g = 0;
g = (1.09 + (0.41 * (Math.Sqrt(50 / b))));
lbl_vertforce.Content = Math.Round((b * g * 9.81), 2);
So, tb_weight is a textbox where the input is made, and lets say the input is 5000, the label lbl_vertforce is showing 119,61 and according to my calculator, it should show 119,74. What is wroing here?
Doubles are not 100% precise and can vary in the least common digits. If you want exact precision you need to use Decimal type which has a bigger memory foot print, but was designed to be very precise. Unfortunately Math.Sqrt is not overloaded for Decimal and only works on doubles. I have provide code I found in another posting discussing the subject of Decimal Square roots: Performing Math operations on decimal datatype in C#?
public void YourCodeModifiedForDecimal()
{
int a = Int32.Parse(tb_weight.Text);
decimal b = 0;
b = (a* 1.03m) / 1000m;
decimal g = 0;
g = (1.09m + (0.41m * (Sqrt(50m / b))));
lbl_vertforce.Content = Math.Round((b* g * 9.81m), 2);
}
public static decimal Sqrt(decimal x, decimal? guess = null)
{
var ourGuess = guess.GetValueOrDefault(x / 2m);
var result = x / ourGuess;
var average = (ourGuess + result) / 2m;
if (average == ourGuess) // This checks for the maximum precision possible with a decimal.
return average;
else
return Sqrt(x, average);
}
You need to round g to 2 decimal places to get 119.74 in the final calculation.
g = Math.Round(1.09 + (0.41 * (Math.Sqrt(50 / b))), 2);

making double variables lower than 1

in my ASP.NET project i did a survey page that uses Application to save the votes. I have a problem with the making of the percentages amount. I've tried many things. here is the problematic part of my code:
double x = (count / sum) ;
double f = (count1 / sum) ;
double g = (count2 / sum) ;
double h = (count3 / sum) ;
if (sum > 0)
{
a = (int)x * 100;
b = (int)f * 100;
c = (int)g * 100;
d = (int)h * 100;
}
I used breakpoints and figured out that the problem was in the double variables: the (count/sum) equals 0 anyway.
I'm assuming count and sum are integer types.
The result of division of 2 integers is a truncated integer.
You need to cast one side of the division to a double, then the result will be double
So
((double)count)/sum
What are the datatypes of count, count[1-3] and sum? If they are integral types, then integer division is performed. This
int x = 100 ;
int y = 300 ;
double z = x / y ;
yields the value 0.0 for z.
Try something like
double h = (double) ( count3 / sum ) ;
You might also want to move your test for sum > 0 up: as coded, if sum is zero, you'll throw a DivideByZeroException before you get to your test, thus rendering your test moot.
Your count and sum variables are probably integers. Cast one of them to double:
double x = count / (double)sum;
UPDATE:
Actually, if you want the percentage as an integer, you can skip the doubles altogether:
int a = 100 * count / sum;

Why do these division equations result in zero?

The result of all of the division equations in the below for loop is 0. How can I get it to give me a decimal e.g.:
297 / 315 = 0.30793650793650793650793650793651
Code:
using System;
namespace TestDivide
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i <= 100; i++)
{
decimal result = i / 100;
long result2 = i / 100;
double result3 = i / 100;
float result4 = i / 100;
Console.WriteLine("{0}/{1}={2} ({3},{4},{5}, {6})", i, 100, i / 100, result, result2, result3, result4);
}
Console.ReadLine();
}
}
}
Answer:
Thanks Jon and everyone, this is what I wanted to do:
using System;
namespace TestDivide
{
class Program
{
static void Main(string[] args)
{
int maximum = 300;
for (int i = 0; i <= maximum; i++)
{
float percentage = (i / (float)maximum) * 100f;
Console.WriteLine("on #{0}, {1:#}% finished.", i, percentage);
}
Console.ReadLine();
}
}
}
You're using int/int, which does everything in integer arithmetic even if you're assigning to a decimal/double/float variable.
Force one of the operands to be of the type you want to use for the arithmetic.
for (int i = 0; i <= 100; i++)
{
decimal result = i / 100m;
long result2 = i / 100;
double result3 = i / 100d;
float result4 = i / 100f;
Console.WriteLine("{0}/{1}={2} ({3},{4},{5}, {6})",
i, 100, i / 100d, result, result2, result3, result4);
}
Results:
0/100=0 (0,0,0, 0)
1/100=0.01 (0.01,0,0.01, 0.01)
2/100=0.02 (0.02,0,0.02, 0.02)
3/100=0.03 (0.03,0,0.03, 0.03)
4/100=0.04 (0.04,0,0.04, 0.04)
5/100=0.05 (0.05,0,0.05, 0.05)
(etc)
Note that that isn't showing the exact value represented by the float or the double - you can't represent 0.01 exactly as a float or double, for example. The string formatting is effectively rounding the result. See my article on .NET floating binary point for more information as well as a class which will let you see the exact value of a double.
I haven't bothered using 100L for result2 because the result would always be the same.
Try
i / 100.0
because i is an int: i / 100 performs integer division, then the result, that is always 0, is casted to the target type. You need to specify at least one non-int literal in your expression:
i / 100.0
Because i is an integer and 100 is an integer...so you have an integer division
Try (decimal)i / 100.0 instead
No matter where you store it, an integer divided by an integer will always be an integer.
You need to force a floating point operation "double / double" instead of an "int / int"
double result = (double)297 / (double)315 ;
this is integer division whatever the type of variable you storing in,
so int / int = int
double result3 = ((double)i) / 100;
Because i is a int value and you divide by an integer so the result is an integer ! and so you need to divide by 100.0 to have an implicit cast in float or specify 100f or 100d
In my case I had only vars and no int
float div = (var1 - var2) / float.Parse(var1.ToString());

Categories