Reputation: 81
I'm trying to display the result of a percentage calculation in a view. Round and Score are coming from a local database, I want to count the number of rounds recorded, add up the values stored in Score, then output result as a percentage. I hope that makes sense!
Currently I have a few values stored in the database but the result I am getting all the time is zero. Values from the database do not seem to be getting into the calculation method.
Thanks so much in advance!
Controller:
public ActionResult CalcPercent()
{
PracticeViewModel pvm = new PracticeViewModel();
var rounds = _context.Practices3.Select(r => r.Round).Count();
var scores = _context.Practices3.Sum(s => s.Score);
pvm.Percentage = scores / (rounds * 10) * 100;
return View(pvm);
}
Model:
public class Practice
{
[Key]
public int Id { get; set; }
public DateTime Date { get; set; }
public int Score { get; set; }
public double Round { get; set; }
}
ViewModel:
public class PracticeViewModel
{
public int Percentage { get; set; }
}
View:
@model EmailAndPDF_Test.Models.PracticeViewModel
<p> @Model.Percentage</p>
Upvotes: 0
Views: 246
Reputation: 43900
Error public INT Percentage { get; set; }; you have to change it to public DOUBLE Percentage { get; set; };
Why instead var rounds = _context.Practices3.Select(r => r.Round).Count(); you don't use _context.Practices3.Count(); Maybe you mean _context.Practices3.Where(r => r.Round>0).Count();?
Try instead of pvm.Percentage = scores / (rounds * 10) * 100; to use pvm.Percentage = Math.Round((scores / (rounds * 10)) * 100,3);
Upvotes: 1