Click here to Skip to main content
15,887,027 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
How to convet this percentage calculation of sql in c# function?

SQL
select isnull(CAST(ceiling(ROUND(cast(cast(sum(value) AS NUMERIC) / cast(sum(total) AS NUMERIC) * 100 AS DECIMAL(8, 2)), 0)) AS INT), 0) as percentage
Posted
Updated 5-Mar-16 4:33am
v2
Comments
OriginalGriff 5-Mar-16 4:15am    
This is not a good question - we cannot work out from that little what you are trying to do.
Remember that we can't see your screen, access your HDD, or read your mind.
So explain what you are trying to do, what you have tried, where you are stuck, and what you need help with.
And probably, why your SQL is casting stuff so much...
Use the "Improve question" widget to edit your question and provide better information.

C#
var value = 123.45;
var total = 1000.1;
var perc = total == 0 ? 0 : Convert.ToInt32((value * 100) / total);
 
Share this answer
 
Comments
Ashishmau 5-Mar-16 5:48am    
Its not working properly. Suppose value = 4 and total = 31. In this case, sql query returns 13 while your above code returns 12. I want exact returns given by sql query.
RickZeeland 5-Mar-16 9:32am    
var value = 4.0;
var total = 31.0;
var perc = total == 0 ? 0 : Convert.ToInt32(Math.Round((value * 100) / total));
CHill60 5-Mar-16 10:34am    
Did you know you can use the Improve solution link to change your solution
Check this:
C#
double avalue = 4.0;
double total = 31.0;

var result = total == 0 ? 0 : Math.Round((avalue/total)*100);
Console.WriteLine("{0}:{1}={2}", avalue, total, result);
 
Share this answer
 
And another option...

This one assumes that value and total are integers and you want an integer result
C#
var value = 4;
var total = 31;
var perc = (total == 0) ? 0 : (int)Math.Ceiling(value * 100.0 / total);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900