Format Decimal column

Padmanabhan, Venkatesh 246 Reputation points
2021-01-17T07:35:59.617+00:00

Hi.
I am trying to format a column, so that value is displayed in 30 characters before the decimal and 4 places after the decimal.

Example: +000000000000000000000002500000.0000 ( + or - depending on the value ) .

I tried the below:

select CAST(ISNULL(NULLIF(columnName, ''),0) AS DECIMAL(30,4)) from table.

But this does result in the patter required. How to format this , as shown in the example?
Thanks

SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2021-01-17T08:22:14.187+00:00

    Try this:

    select format( cast(isnull(nullif(columnname, ''),0) as decimal(34,4)), '+000000000000000000000000000000.0000;-000000000000000000000000000000.0000')
    
    1 person found this answer helpful.
    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Abdulhakim M. Elrhumi 356 Reputation points
    2021-01-17T08:47:19.637+00:00

    Hi
    57365-num.png

    Best Regards.
    Please remember to mark the replies as answers if they help.

    0 comments No comments

  2. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2021-01-17T10:31:16.277+00:00

    Here is an alternate solution:

    DECLARE @d decimal(30,4) = 2221.2346
    SELECT IIF(@d >= 0, '+', '-') + replace(str(abs(@d), 35, 4), ' ', '0')
    

    This could perform better if the data set is large. The format function is implemented in the CLR and that context switch comes with a price.

    0 comments No comments

  3. tibor_karaszi@hotmail.com 4,316 Reputation points
    2021-01-18T11:16:45.01+00:00

    Note that the (working) suggestions you got in this thread returns a string data type, not a numeric data type. You can't return a numeric type and enforce some specific formatting, it is the client app the decides on how to represent your data. Se as soon as we talk about some specific format you either have to find a suitable type where your client app give you the presentation you want (not possible for your case) or return it as a string.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.