Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have amount value for which I have to do the following

1. Should be fitted in 10 chars
2. left pad with zeros the remaining chars apart from the value
3. Should be showing - ve sign for the amount field if present
4. if the amount is -ve '-' symbol should be displayed in front of the value.

For eg: there is a value -45.10

it should be printed as -000045.10

Below is what I have done so far.

Any help is very appreciated

SQL
select REPLACE(CONVERT(CHAR(10),tbl.Amount),' ','0')
from table tbl


"0000-40.00" is the result I am getting with the above query.

If a -ve sign is present as above in the string it should be in the first place "-000040.00"
Posted

Try:
SQL
SELECT CASE WHEN MyColumn < 0 THEN '-' + RIGHT('00000000' + CONVERT(NVARCHAR,-MyColumn), 9) ELSE RIGHT('000000000' + CONVERT(NVARCHAR,MyColumn), 10) END As NumericValue FROM MyTable
 
Share this answer
 
Comments
anupama962010 7-Feb-15 12:37pm    
Thank you the above worked
This should work:

SQL
SELECT STUFF(CAST(Val AS VARCHAR(10)),CASE WHEN Val<0 THEN 2 ELSE 1 END,0,REPLICATE('0',10-LEN(CAST(Val AS VARCHAR(10)))))


but it performs the CAST twice, which I don't like. I would use a Common Table Expression to eliminate the duplicated effort.


SQL
WITH cte0 AS
(
    SELECT -45.10 Val
)
, cte1 AS
(
    SELECT Val , CAST(Val AS VARCHAR(10)) ValStr FROM cte0
)
SELECT STUFF(ValStr,CASE WHEN Val<0 THEN 2 ELSE 1 END,0,REPLICATE('0',10-LEN(ValStr)))
FROM cte1



Or, if you can upgrade, you can use the FORMAT function:

SQL
SELECT FORMAT(-45.10,'000000.00')
 
Share this answer
 
v2
Comments
anupama962010 7-Feb-15 12:37pm    
Thank you. It is working
Try this:
SQL
DECLARE @number decimal(10,2)
SET @number = -45.10
SELECT
   CASE
      WHEN @number < 0 THEN
         '-' + RIGHT('000000000' + CONVERT(VARCHAR(9), ABS(@number)), 9)
      ELSE
         RIGHT('0000000000' + CONVERT(VARCHAR(10), @number), 10)
   END
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900