Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a number to a numeric, comma-separated formatted string?

Is there an easy way to convert a number (in my case an integer) to a comma separated nvarchar string?

For instance, if I had an int value of 1000000 stored in a field, how can I convert it to an nvarchar string with the outputted result of "1,000,000"?

I could easily write a function to do this but I wanted to be sure there wasn't an easier way involving a call to either CAST or CONVERT.

like image 807
RLH Avatar asked Jun 10 '11 16:06

RLH


People also ask

How do you convert a string to a comma with numbers?

To convert a comma separated string to a numeric array:Call the split() method on the string to get an array containing the substrings. Use the map() method to iterate over the array and convert each string to a number. The map method will return a new array containing only numbers.

How are commas separated in numbers?

In English, we use commas to separate numbers greater than 999. We use a comma every third digit from the right. More than 50,000 people turned up to protest.


2 Answers

The reason you aren't finding easy examples for how to do this in T-SQL is that it is generally considered bad practice to implement formatting logic in SQL code. RDBMS's simply are not designed for presentation. While it is possible to do some limited formatting, it is almost always better to let the application or user interface handle formatting of this type.

But if you must (and sometimes we must!) use T-SQL, cast your int to money and convert it to varchar, like this:

select convert(varchar,cast(1234567 as money),1) 

If you don't want the trailing decimals, do this:

select replace(convert(varchar,cast(1234567 as money),1), '.00','') 

Good luck!

like image 199
Michael Ames Avatar answered Oct 14 '22 08:10

Michael Ames


For SQL Server 2012, or later, an easier solution is to use FORMAT ()Documentation.
EG:

SELECT Format(1234567.8, '##,##0')  

Results in: 1,234,568

like image 42
Jacob Thomas Avatar answered Oct 14 '22 09:10

Jacob Thomas