Sunday, September 9, 2007

Pad zeros to a numeric number for a given length

-- Pad zeros to a numeric number for a given length
-- Note: total length specified includes decimal point and digits after the decimal point

declare @number numeric(10,4)
set @number = 1234.56
select replace(str(@number,10,4),' ','0') -- output: 01234.5600

-- You can try the following variations

select replace(str(@number,10,3),' ','0') -- output: 001234.560

select replace(str(@number,10,2),' ','0') -- output: 0001234.56

select replace(str(@number,10,1),' ','0') -- output: 00001234.6

select replace(str(@number,10,0),' ','0') -- output: 0000001235

No comments: