Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Decimal to Varchar

I have a decimal column in a table defined as decimal(8,3). I would like to include this column in a Select statement, convert it to a Varchar and only display two decimal places. I can't seem to find the right combination of options to do this because everything I try still produces three decimal places.

like image 638
Hosea146 Avatar asked Apr 06 '11 19:04

Hosea146


People also ask

Can a decimal be a varchar?

3 Answers. The short answer is: No, it will hurt performance. The longer answer: VARCHAR fields are variable length, meaning, that the formatting of the database blocks cannot pre-account for the size of the data filling in there.

Can we convert int to varchar in SQL?

Converting int to string/varchar using Cast() So, in the above example, we have declared a variable of integer data type and assigned a value to the variable. After this, we are using the Cast() function to convert the variable to the varchar data type of length 10. And the query will return the following result.


2 Answers

Here's one way:

create table #work (   something decimal(8,3) not null  )  insert #work values ( 0 ) insert #work values ( 12345.6789 ) insert #work values ( 3.1415926 ) insert #work values ( 45 ) insert #work values ( 9876.123456 ) insert #work values ( -12.5678 )  select convert(varchar,convert(decimal(8,2),something)) from #work 

if you want it right-aligned, something like this should do you:

select str(something,8,2) from #work 
like image 91
Nicholas Carey Avatar answered Sep 25 '22 23:09

Nicholas Carey


If you are using SQL Server 2012, 2014 or newer, use the Format Function instead:

select Format( decimalColumnName ,'FormatString','en-US' ) 

Review the Microsoft topic and .NET format syntax for how to define the format string.

An example for this question would be:

select Format( MyDecimalColumn ,'N','en-US' ) 
like image 43
Andrew Avatar answered Sep 24 '22 23:09

Andrew