473,748 Members | 6,418 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I format an integer

How do I format an integer. Add commas.

1234565 1,234,565

TIA
Jul 23 '05 #1
3 19230
stevek wrote:
How do I format an integer. Add commas.

1234565 1,234,565

TIA


Hi SteveK,

Create the following function

*************** * START HERE *************** *
CREATE FUNCTION [dbo].[FormatNumber] (

@number decimal(38,15),
@decimalplaces int=0,
@format varchar(115)='' ,
@ifzero varchar(115)=''
) RETURNS varchar(256)
AS BEGIN
/*
Valid @Format arguments (space between args is ignored)
nothing - returns the number unformatted
$ - return the number preceded by a '$' sign
% - return the number followed by a '%' sign
, - place a , every 3 zeros in the whole number portion (thousands)
c - divide the number by 100 - intended to calc percent values
i - returns integer portion only with no formatting except commas if
requested
d - returns the decimal portion only with no formatting except commas
if requested
b - returns a blank string for 0 values
( - encloses negative numbers in brackets
l - use leading zero
r[int]r - rounds number outside of the decimal context
z[int]z - zero fills to [int] width
*/

DECLARE @fmtxt varchar(25), @parsetxt varchar(50)
, @parsetxtdec varchar(50)
, @decptloc int, @zerotext varchar(100)
, @intpart varchar(25), @decpart varchar(25)
, @ERR_type varchar(15), @roundto varchar(2)
, @fillto varchar(50), @fillto# varchar(2)

--A little error checking is in order
IF @number IS NULL
RETURN '{ERR-null passed}'
ELSE IF @decimalplaces < 0
RETURN '{ERR-decimal spec <0}'
ELSE IF @decimalplaces >15
RETURN '{ERR-decimal spec >15}'

-- Handle zero values first
IF @number = 0 RETURN @ifzero

-- Now 'C'alculate the percentage if requested using the '%c' arg.
IF CHARINDEX('%c', @FORMAT) > 0 SET @number = @number * 100

-- Do rounding outside if applicable
IF CHARINDEX('r',@ FORMAT) > 0 BEGIN
SET @roundto = SUBSTRING(@FORM AT,CHARINDEX('r ', @FORMAT)+1, 115)
SET @roundto = LEFT(@roundto,C HARINDEX('r',@r oundto)-1)
SET @number = round(@number,c ast(@roundto as integer))
END

-- Get the parsetext variable
IF CHARINDEX(',',@ FORMAT) > 0
SET @parsetxt = CONVERT(varchar (100),CAST(@num ber as money),1)
ELSE
SET @parsetxt = CONVERT(varchar (100), @number)

-- Grab some basic stuff
SET @decptloc = ISNULL(CHARINDE X('.',@parsetxt ),0)

IF @decptloc = 0
RETURN @parsetxt
ELSE
SET @intpart = SUBSTRING(@pars etxt,1,@decptlo c-1)

-- Handle leading zeros
IF CHARINDEX('l',@ FORMAT) = 0 AND @intpart = '0' SET @intpart = ''

-- Now build the decimal portion of the result
SET @parsetxt = CONVERT(varchar (100),ROUND(@nu mber,@decimalpl aces),2)
SET @decptloc = ISNULL(CHARINDE X('.',@parsetxt ),0)
IF @decimalplaces = 0
SET @decpart = ''
ELSE
SET @decpart = LEFT(SUBSTRING( @parsetxt
+ REPLICATE('0',@ decimalplaces)
,@decptloc
,@decptloc+50)
,@decimalplaces +1)

--ASSEMBLE THE RESULTS --

-- for just integer portion
IF CHARINDEX('i',@ FORMAT) > 0
RETURN @intpart
-- for just decimal portion
IF CHARINDEX('d',@ FORMAT) > 0
RETURN + @decpart

SET @fmtxt = @intpart + @decpart
--SET @fmtxt = @intpart +'*'+ @decpart

-- Handle brackets if requested
IF CHARINDEX('(',@ FORMAT) > 0 AND @number < 0
SET @fmtxt = '(' + RIGHT(@fmtxt,LE N(@fmtxt)-1) + ')'

-- Add the symbols
IF CHARINDEX('$',@ FORMAT) > 0
SET @fmtxt = '$' + @fmtxt
ELSE IF CHARINDEX('%',@ FORMAT) > 0
SET @fmtxt = @fmtxt + '%'

--Handle zero filling
IF CHARINDEX('z',@ FORMAT) > 0 BEGIN
SET @fillto = SUBSTRING(@FORM AT,CHARINDEX('z ',@FORMAT)+1,11 5)
SET @fillto# = CAST(LEFT(@fill to,CHARINDEX('z ',@fillto)-1) as INT)
SET @fmtxt = RIGHT(REPLICATE ('0',@fillto#) + @fmtxt,@fillto# )
END

RETURN @fmtxt

END
GO

*************** * END HERE *************** *

Now we need to grant access to it:

GRANT EXEC on dbo.FormatNumbe r to PUBLIC
GO

and to use it do the following:

declare @testnum int
SET @TestNum = 123456789

select dbo.FormatNumbe r (@TestNum, '0', ',', 'zero') as [Integer]

Good luck

Michael van der Veeke
michaelvanderve eke AT borderexpress DOT com DOT au
Jul 23 '05 #2
Formatting and presentation usually belong in the client application,
not the server. The formatting above is not correct in many European
languages, for example - by doing it on the client you can use the
correct locale information for different clients, or use formatting
masks/functions like printf or whatever your preferred development
language has.

Simon

Jul 23 '05 #3
I agree with Simon that data formatting is best performed on in the
presentation layer rather than in SQL. That said, you can use CONVERT to
add commas and string functions to remove extraneous characters.

SELECT
REVERSE(SUBSTRI NG(REVERSE(CONV ERT(varchar(20) , CAST(1234565 AS money),
1)), 4, 20))

--
Hope this helps.

Dan Guzman
SQL Server MVP

"stevek" <so*****@somewh ere.org> wrote in message
news:IV******** *************@b gtnsc05-news.ops.worldn et.att.net...
How do I format an integer. Add commas.

1234565 1,234,565

TIA

Jul 23 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2303
by: Josiah Carlson | last post by:
Good day everyone, I have produced a patch against the latest CVS to add support for two new formatting characters in the struct module. It is currently an RFE, which I include a link to at the end of this post. Please read the email before you respond to it. Generally, the struct module is for packing and unpacking of binary data. It includes support to pack and unpack the c types: byte, char, short, long, long long, char, *, and...
6
30163
by: J | last post by:
Would anyone know if there a type tag to format a double? I have f for floating point, but cannot find one for double.
3
5642
by: marwa mohamed | last post by:
salamo alikom hi all when i run report that includes image control linked to a field in the table that contains the image path(on the server)and the record source of the report contains over 30 records a messege shows saying: "Microsoft Access doesn't support the format of the file'file path\filename.jpg' or file is too large.Try converting the file to BMP or GIF format". I want to know which one is the problem (the size) or (the format...
14
7140
by: L Mehl | last post by:
I tested a FE/BE application developed in A2000 on a A2002 machine and got this message when exiting the app. Clicking the only available button "OK", exits the application, as intended. The FE is just the mdb, not an mde. FE and BE are in different directories on the same machine. Are there settings, preferably via code, that I can add to stop this error? Thank you for any help.
16
4019
by: Al Reid | last post by:
First, I'm using vb2005. I have a string that is read from a barcode reader into a TextBox. The string is 6 characters long and represents a date (mmddyy). I want to display it to the user in a date format of "mm/dd/yy" For example the barcode contains "112303" and I want to format it to display "11/23/03" If I use the microsoft.visualbasic.strings.format with a format string of "##/##/##" or "00/00/00" I get the format string in the...
2
1570
by: gjuro kladaric | last post by:
hi there, I am just learning about IFormattable, ICustomFormatter, IFormatProvider and the like... although being a bit tricky to understand, it becomes clear after some clicking and readying... what is not clear to me and constitutes my question is:
20
35608
by: andreas | last post by:
When I copy a vb.net project using date formats from one PC with a windows date format f.e. dd/mm/yyyy to another PC having a format yy/mm/dd then I get errors. How can I change for a while in the project the date format in vb.code ( not in Windows) and how can I find out which date format the PC Windows is using. Thanks for any response
11
2256
by: RipperT | last post by:
Don't know if this group covers web apps, but here goes. In VS 2005, I am trying to get variables to hold thier values during postback from the server. I convert a text box's user-keyed value to an integer and assign it to a module level variable, then convert the variable and assign it to a hidden text box, setting it's EnableViewState to true so it returns with the reload. Then in the form's load event, I attempt to convert the contents...
2
2146
by: Dhananjay | last post by:
Hi all , I have got problem when i am tring to exportGridview Data into Excel format. It is going into text format ,but what i want is if the field is number/currency then it should go into number/currency format itself .Data exported to excel are all exported as text. Export to excel should maintain the formatting like numbers and money should be numbers and money in excel .
0
9534
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9366
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9241
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8239
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4597
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3303
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2777
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.