Monday, March 16, 2009

Add '0' to Fixed precision and add '0' to scale numbers


DECLARE @PadChar CHAR(1)
DECLARE @FinalLength INTEGER
DECLARE @SourceString VARCHAR(19)
SET @PadChar = '0'
SET @FinalLength = 5

--Which Gives 2 decimal Digits

SELECT CONVERT(VARCHAR(10),CONVERT(MONEY,2))

--The follwing which adds Fixed precision(if there is 1 digit,
--it adds 0 to previous of the 1 and gives 01.00 as ouput)
-- The output is in the format of 00.00

SET @SourceString = '2'
SELECT RIGHT( REPLICATE(@PadChar,@FinalLength - LEN(@FinalLength)) +
CONVERT(VARCHAR(10),CONVERT(MONEY,@SourceString)), 5)

SET @SourceString = '2.0'
SELECT RIGHT( REPLICATE(@PadChar,@FinalLength - LEN(@FinalLength)) +
CONVERT(VARCHAR(10),CONVERT(MONEY,@SourceString)), 5)

SET @SourceString = '0.2'
SELECT RIGHT( REPLICATE(@PadChar,@FinalLength - LEN(@FinalLength)) +
CONVERT(VARCHAR(10),CONVERT(MONEY,@SourceString)), 5)

SET @SourceString = '00.2'
SELECT RIGHT( REPLICATE(@PadChar,@FinalLength - LEN(@FinalLength)) +
CONVERT(VARCHAR(10),CONVERT(MONEY,@SourceString)), 5)

SET @SourceString = '0.20'
SELECT RIGHT( REPLICATE(@PadChar,@FinalLength - LEN(@FinalLength)) +
CONVERT(VARCHAR(10),CONVERT(MONEY,@SourceString)), 5)

No comments: