Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format number as percent in MS SQL Server

I am trying to simply format a number as a percent with two decimal places. If it is 37 divided by 38 (aka .973684210526315789), I would like it to show 97.36 % in the SQL output. I know it is recommended to do formatting in the Application, however this is for an automated export. This is using SQL Server 2008.

Here is what I have now:

select CONVERT(VARCHAR(50),cast(37 as decimal)/cast(38 as decimal)*100)+' %' AS [%] 

If you could explain what the various parameters are as well in any function that would be helpful.

like image 846
user3513237 Avatar asked May 06 '15 23:05

user3513237


People also ask

Is there a percent data type in SQL?

The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a percentage.

How do you convert a whole number to a decimal in SQL?

SQL Server ROUND() Function The ROUND() function rounds a number to a specified number of decimal places. Tip: Also look at the FLOOR() and CEILING() functions.


1 Answers

In SQL Server 2012 and later, there is the FORMAT() function. You can pass it a 'P' parameter for percentage. For example:

SELECT FORMAT((37.0/38.0),'P') as [Percentage] -- 97.37 % 

To support percentage decimal precision, you can use P0 for no decimals (whole-numbers) or P3 for 3 decimals (97.368%).

SELECT FORMAT((37.0/38.0),'P0') as [WholeNumberPercentage] -- 97 % SELECT FORMAT((37.0/38.0),'P3') as [ThreeDecimalsPercentage] -- 97.368 % 
like image 113
jbeldock Avatar answered Sep 19 '22 15:09

jbeldock