USE [MyTestDb]
GO
DROP FUNCTION [dbo].[udf_Global_PadTwoDecimalDigitString]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[udf_Global_PadTwoDecimalDigitString](@StringDecimalValue varchar(25))
RETURNS varchar(25)
AS
BEGIN
DECLARE
@Value varchar(25)
,@ValueAsFloat decimal(20, 3)
,@ValueAsFloatBackToVarchar varchar(25)
,@ValueAsVarcharWith2Decimal varchar(25)
SET @Value = @StringDecimalValue
-- Ensure that it has decimal values, if not, forced to add .00
SET @Value = @Value + (CASE WHEN CHARINDEX('.', @Value) = 0 THEN '.00' ELSE SPACE(0) END)
-- Secret sauce:
SET @ValueAsFloat = CAST(@Value AS decimal(20, 3)) + .001
SET @ValueAsFloatBackToVarchar = CAST(@ValueAsFloat AS decimal(20, 3))
SET @ValueAsVarcharWith2Decimal = SUBSTRING(@ValueAsFloatBackToVarchar, 1, CHARINDEX('.', @ValueAsFloatBackToVarchar) + 2)
RETURN @ValueAsVarcharWith2Decimal
END
GO
Comments
Post a Comment