Create Function [dbo].[Format]
(
    @Number Float,
    @DecimalPlaces Int
)
Returns Varchar(50)
As
Begin
    Declare @Formatted Varchar(50)
    Declare @Sign Char(1) = Case When @Number < 0 Then '-' Else '' End
    Declare @AbsNumber Float = Abs(@Number)

    -- جدا کردن بخش صحیح و اعشاری
    Declare @IntegerPart Bigint = Floor(@AbsNumber)
    Declare @DecimalPart Float = @AbsNumber - @IntegerPart

    -- تبدیل بخش صحیح با جداکننده هزارگان
    Declare @IntStr Varchar(30) = ''
    While @IntegerPart >= 1000
    Begin
        Set @IntStr = ',' + Right('000' + Cast(@IntegerPart % 1000 As Varchar), 3) + @IntStr
        Set @IntegerPart = @IntegerPart / 1000
    End
    Set @IntStr = Cast(@IntegerPart As Varchar) + @IntStr

    -- تبدیل بخش اعشاری
    Declare @DecStr Varchar(20) = ''
    If @DecimalPlaces > 0
    Begin
        Set @DecStr = '.' + Right(Replicate('0', @DecimalPlaces) + 
                      Cast(Round(@DecimalPart * Power(10, @DecimalPlaces), 0) As Varchar), @DecimalPlaces)
    End

    Set @Formatted = @Sign + @IntStr + @DecStr
    Return @Formatted
End
