views:

51

answers:

1

i want to place negative value in bracket like -2000 to (2000)

for that i made a which is converting -1361236.75886298 to (1.36124e+006)

the function that i made for this is :

ALTER function [dbo].[IsNegative](
@Number NVARCHAR (500)
)
Returns nvarchar (200)
as
begin 
Declare @Number2 FLOAT
set @Number2=Cast (@Number as float)
Declare @result nvarchar (200)
if ( @Number2  <=0.0)
begin
Set @result='('+Substring (@Number,2,len(@Number))+')'
end
else        
begin
Set @result = @Number 
end
return @result
end

i want accurate answere thanx in advance

+2  A: 

What is the proposed usage of this function?

This type of formatting is probably best left to the presentation layer (assuming that there is a presentation layer)

The following function might be suitable for formatting individual standalone values that are to be concatenated into a longer string. It would probably not be suitable for formatting multiple values as you would want these all to aligned at the decimal point. For this you could investigate the str function.

CREATE FUNCTION [dbo].[IsNegative](
@Number DECIMAL(38,16)
)
RETURNS VARCHAR (50)
WITH RETURNS NULL ON NULL INPUT
AS
BEGIN 
DECLARE @result VARCHAR (50)

/*Trim trailing zeroes and decimal point*/
SET @result = REPLACE(RTRIM(REPLACE(REPLACE(RTRIM(REPLACE(@Number,'0', ' ')),' ', '0'),'.', ' ')),' ', '.')

IF @Number < 0
    SET @result = '(' + SUBSTRING(@result,2,LEN(@result)) + ')'

RETURN @result
END


GO

WITH T AS
(
SELECT -1361236.75886298 AS N UNION ALL
SELECT -2000 UNION ALL
SELECT 2000
)

SELECT 
     [dbo].[IsNegative](N)
FROM T

Returns

(1361236.75886298)
(2000)
2000

Is that what you need?

Martin Smith