INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

User-Defined Functions

Formating Numbers via T/SQL by mrdenny
Posted: 10 Nov 03

Often I've been requested to write a SQL Script that formats the numbers into a way that is easy for people to read.  Complete with commas, and decimals.  Since SQL doesn't have a way to do this internally, I came up with this little function.  When calling the function there are two parameters that need to be passed.  The first is the number you want to convert.  The second is weather or not you want to display decimals.

The default number of decimal places to show is 2.  This can be changed in the second line as needed.  To hid decimals set the @ShowDecimal parameter to 0.  To show them, set it to 1.

To call the function you can use it like this:

select name, dbo.FormatNumber(id, 0)
from master.dbo.sysobjects


Below is the actual function.

CREATE Function FormatNumber
(@RawNumber numeric(32,2) = 0,
    @ShowDecimal as bit = 0
)
returns varchar(200) AS
BEGIN
    declare @FormattedNumber as varchar(100)
    declare @AfterDecimal as varchar(100)
    declare @i as int
    declare @j as int
    set @i = 0
    set @j = 0
    set @FormattedNumber = convert(bigint, @RawNumber)
    set @AfterDecimal = @RawNumber
    if charindex('.', @AfterDecimal) <> 0
    BEGIN
        set @AfterDecimal = '.' + right(@AfterDecimal, len(@AfterDecimal)-charindex('.', @AfterDecimal))
    END
    ELSE
    BEGIN
        set @AfterDecimal = ''
    END
    
    
    while @i <> len(@FormattedNumber)
    BEGIN
        if @j = 3
        BEGIN
            set @j = -1
            set @FormattedNumber = left(@FormattedNumber, len(@FormattedNumber)-@i) + ',' + right(@FormattedNumber, @i)
        END
        set @j = @j + 1
        set @i = @i + 1
    END
    if @ShowDecimal <> 0
        set @FormattedNumber =  @FormattedNumber + @AfterDecimal
    return @FormattedNumber
END


Back to Microsoft SQL Server: Programming FAQ Index
Back to Microsoft SQL Server: Programming Forum

My Archive

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close