Automatically Round off numbers to the nearest digit

I was solving a requirement where data entered into a table contained decimals. However the user had a requirement of automatically rounding off the decimals to the nearest digit before inserting into the table. The SQL statements could not be changed to make use of the Round() function. So one of the ways of solving this was to use the numeric datatype in the table definition as shown below:

DECLARE @TmpTable TABLE
(
id int,
amount numeric(7,0)
)

INSERT INTO @TmpTable VALUES (1, 5.556233)
INSERT INTO @TmpTable VALUES (1, 2.123953)
INSERT INTO @TmpTable VALUES (1, 3.753433)

SELECT * FROM @TmpTable

OUTPUT

image

As you can see, data stored into the table automatically gets rounded off.


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

3 comments:

Dave Levy said...

Seems kind of risky to rely on implied functionality instead of just using the Round (http://msdn.microsoft.com/en-us/library/ms175003.aspx) statement.

Does using the temp table buy you anything else?

Suprotim Agarwal said...

Dave: Nice point. The client did not want to change the sql statement. They were ok making changes in the schema instead, hence the solution. I have added that point to the post.

KIRTAN KHATSURIYA said...

what if i do not want round values? how can i stop it?