Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Rounding in SQL With Decimal Types

Tags:

sql

sql-server

I am working on an exercise that requires me to call a stored procedure within another procedure. The procedure being called simply divides two numbers, however the result seems to be rounded upwards.

In the exercise, 5.0 is divided by 10.0, and the result is 1. The result should obviously be 0.5. The goal is to make the output display correctly without just changing the DECIMAL type.

Here is the code:

GO

CREATE PROCEDURE uspDivide2Numbers
     @decValue1 AS DECIMAL
    ,@decValue2 AS DECIMAL
    ,@decResult AS DECIMAL OUTPUT
AS
SET NOCOUNT ON

SELECT @decResult = @decValue1 / @decValue2

GO


CREATE PROCEDURE uspCallAnotherStoredProcedure
AS
SET NOCOUNT ON

DECLARE @decResult AS DECIMAL

EXECUTE uspDivide2Numbers 5.0, 10.0, @decResult OUTPUT

SELECT @decResult AS decResult

GO

uspCallAnotherStoredProcedure

Any help would be appreciated, I don't really understand why decimal values round in the first place, so it's probably an issue on my end.

like image 936
user3530169 Avatar asked Jan 25 '15 20:01

user3530169


People also ask

How do I stop rounding decimals in SQL?

If you specify a precision and scale for the type, like decimal(18,2) , it can handle numbers that are not integers. The scale is how many digits will be stored after the decimal separator. Depending on your needs, you might also consider the float and real floating point data types.

How do you round to 2 decimal places in SQL?

Using ROUND() function with a variable and getting the rounded number to -2 decimal place.

How do you handle decimals in SQL?

Standard SQL requires that DECIMAL(5,2) be able to store any value with five digits and two decimals, so values that can be stored in the salary column range from -999.99 to 999.99 . In standard SQL, the syntax DECIMAL( M ) is equivalent to DECIMAL( M ,0) .

Should I use float or decimal in SQL?

Float stores an approximate value and decimal stores an exact value. In summary, exact values like money should use decimal, and approximate values like scientific measurements should use float. When multiplying a non integer and dividing by that same number, decimals lose precision while floats do not.


1 Answers

The default scale of a decimal is zero, which means that what you have is actually an integer type. So, it's not possible to return the value 0.5 without changing the data type.

If you specify a precision and scale for the type, like decimal(18,2), it can handle numbers that are not integers. The scale is how many digits will be stored after the decimal separator.


Depending on your needs, you might also consider the float and real floating point data types.

like image 178
Guffa Avatar answered Nov 15 '22 08:11

Guffa