nam
nam

Reputation: 23749

Formatting a float value as a percentage in C# is not working

In SQL Server 2012 SSMS, following correctly returns 43.69180299700. In ASP.NET Core, I want to display it as a percentage 43.69%. But the View shown below returns it wrongly as 4,369.18 %. Question: What I may be missing and how can I correct it in View? Note: There is no formatting applied via annotations in either Model or ViewModel. Both have just attributes of type float?.

T-SQL:

select (386771.20/885226.00)*100

ViewModel:

Public class ProfitViewModel
{
    ....
    public float? val1 { get; set; }
    public float? val2{ get; set; }
    public string profit_percent { get; set; }
}

Controller:

....
....
ProfitViewModel ProfitVM = new ProfitViewModel();
....
....
float? val1 = 386771.20;
float? val2 = 885226.00;

ProfitVM.profit_percent = ((float)(val1/ val2) * 100).ToString("P");
....
....
return View(ProfitVM);

View: [Line below displays as 4,369.18 % instead of 43.69%]

....
Total Percentage: <div>@Model.profit_percent</div>
....

Upvotes: 1

Views: 978

Answers (2)

adjan
adjan

Reputation: 13652

Remove the * 100 from the line

ProfitVM.profit_percent = ((float)(val1/ val2) * 100).ToString("P");

Upvotes: 1

JoelFan
JoelFan

Reputation: 38704

It looks like the "P" format handles the multiplying for you. Try not multiplying by 100

Upvotes: 2

Related Questions