I have a problem with a SQL query that I don’tr understand:
I am using WebMatrix with razor syntax.
I want to query my stock table and find how many of my top movers are in stock, as a percentage.
In the code bolock, i have:
var topmovers = db.QueryValue("select COUNT(STOCKCODE) from dbo.STOCK_ITEMS where STOCK_CLASSIFICATION = 170") ?? 0;
var instock = db.QueryValue("select COUNT(STOCKCODE) from dbo.STOCK_ITEMS where STOCK_CLASSIFICATION = 170 and TOTALSTOCK > 0") ?? 0;
var ofpc = instock/topmovers;`
then in the body, i have
@ofpc.ToString("P2")
It returns either 0 or 100, depending on which way around I have the variables instock and topmovers. I want a percentage, not 100% or 0%!
If i go @instock.ToString(); i get 862
If I go @topmovers.ToString(); i get 965
According to my maths, 862/965 is 0.8932 (89.32%)
However, I am getting 0.00% as the result of ofpc when I output it with @ofpc.ToString("P2")
I’m obviously wrong somewhere…
The same problem happens in SQL Server, which does integer division, so:
Always returns 0.
So, you need to cast one of the values to a floating point number. Can you use this expression:
Or something similar? Perhaps:
You can also make the database return a floating point value:
What I’ve done is convert the first count to a float inside SQL. You can undoubtedly do this at the application level, but I’m more familiar with SQL. This should make the
topmoversvariable a float, and the division will be a floating point division.