SQL Server 2008: why this round will not be equal to two decimal places?

SELECT
   ROUND(WeightInOZ / 16, 2)as WeightInLbs
FROM
   Inventory

The result I get looks like an integer of 1.2, etc.

+3
source share
2 answers

Try changing 16 to 16.0

SELECT
   ROUND(WeightInOZ / 16.0, 2)as WeightInLbs
FROM
   Inventory

You see strange results because you are processing the results of your division as a whole, not a decimal. The directive .0tells the sql server to treat it as a decimal number.

UPDATE:

If trailing zero makes fun of you, you can always do this:

SELECT
   CAST(ROUND(WeightInOZ / 16.0, 2) AS NUMERIC(8,2)) as WeightInLbs
FROM
   Inventory
+8
source

The problem is this:

WeightInOZ / 16

Since you are dealing with two integers, SQL Server truncates the remainder, so there is no fractional component to round it.

, , ( ). - 16 16.0.

SELECT
   ROUND(WeightInOZ / 16.0, 2)as WeightInLbs
FROM
   Inventory
+5

Source: https://habr.com/ru/post/1790531/


All Articles