question

Jackson1990-7147 avatar image
0 Votes"
Jackson1990-7147 asked MelissaMa-msft commented

Issue with SQL format

Hi,
Col0 below is one varchar column. I expect it to be shown in format like '####.##' by the code below but it is not OK. What to adjust?

format(cast(col0 as decimal(12,2)),'####.##')


sql-server-generalsql-server-transact-sql
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi @Jackson1990-7147,

Could you please provide some sample data and expected output after doing format?

Best regards,
Melissa

0 Votes 0 ·

See number below
102.9
103.91

I expect to have

0102.90
0103.91

0 Votes 0 ·

Hi @Jackson1990-7147,

Could you please validate all the answers so far and provide any update?

Please remember to accept the answers if they helped. Your action would be helpful to other users who encounter the same issue and read this thread. 

Thank you for understanding!

Best regards,
Melissa

0 Votes 0 ·

See number below
102.9
103.91

I expect to have

0102.90
0103.91

0 Votes 0 ·
TomPhillips-1744 avatar image
0 Votes"
TomPhillips-1744 answered TomPhillips-1744 edited

Just to be clear.

You need to use "0000.00" as the format to have 0 fill.

Please see:
https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings

 DECLARE @tbl TABLE (col0 DECIMAL(18,4))
 INSERT INTO @tbl VALUES
 (123.45),
 (123.4),
 (123),
 (123.456)
    
 SELECT 
 format(cast(col0 as decimal(12,2)),'####.##')
 ,format(cast(col0 as decimal(12,2)),'####.00')
 ,format(cast(col0 as decimal(12,2)),'0000.00')
 FROM @tbl
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Jackson1990-7147 avatar image
0 Votes"
Jackson1990-7147 answered

See number below
102.9
103.91

I expect to have

0102.90
0103.91

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

MelissaMa-msft avatar image
0 Votes"
MelissaMa-msft answered MelissaMa-msft edited

Hi @Jackson1990-7147,

Please have a try with below:

 format(cast(col0 as decimal(12,2)),'0000.00')

OR

 right('0000'+ cast(cast(col0 as decimal(12,2)) as varchar(10)),7)

If above is not working, please provide more sample data and expected output.

Best regards,
Melissa


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.