SQL - 四舍五入数学表达式
SQL - Rounding a math expression
我正在尝试将一个值四舍五入到小数点后两位。但是以下代码中的结果仍然显示小数点后 4 位
select p.ProductName, p.UnitPrice, s.CompanyName, c.CategoryName,
case
when c.CategoryName in ('Condiments', 'Beverages') then round((UnitPrice + (UnitPrice * .2)), 2)
when c.CategoryName in ('meat/poultry', 'seafood') then round((UnitPrice + (UnitPrice * .15)), 2)
when s.CompanyName = 'New Orleans Cajun Delights' then round((UnitPrice + (UnitPrice * .08)), 2)
else p.unitprice
end as NewUnitPrice
from products p
join Categories c on c.CategoryID = p.CategoryID
join Suppliers s on s.SupplierID = p.SupplierID
解决方法是将数据类型改为2点精度。请参阅下面的示例。
SELECT
CAST(2.49532785 AS NUMERIC(32,8)) AS [Original] --Original 8 precision numeric
,ROUND(CAST(2.49532785 AS NUMERIC(32,8)),2) AS [Rounded] --Rounded 8 precision numeric
,CAST(2.49532785 AS NUMERIC(32,2)) AS [Cast] --Original 2 precision numeric
我正在尝试将一个值四舍五入到小数点后两位。但是以下代码中的结果仍然显示小数点后 4 位
select p.ProductName, p.UnitPrice, s.CompanyName, c.CategoryName,
case
when c.CategoryName in ('Condiments', 'Beverages') then round((UnitPrice + (UnitPrice * .2)), 2)
when c.CategoryName in ('meat/poultry', 'seafood') then round((UnitPrice + (UnitPrice * .15)), 2)
when s.CompanyName = 'New Orleans Cajun Delights' then round((UnitPrice + (UnitPrice * .08)), 2)
else p.unitprice
end as NewUnitPrice
from products p
join Categories c on c.CategoryID = p.CategoryID
join Suppliers s on s.SupplierID = p.SupplierID
解决方法是将数据类型改为2点精度。请参阅下面的示例。
SELECT
CAST(2.49532785 AS NUMERIC(32,8)) AS [Original] --Original 8 precision numeric
,ROUND(CAST(2.49532785 AS NUMERIC(32,8)),2) AS [Rounded] --Rounded 8 precision numeric
,CAST(2.49532785 AS NUMERIC(32,2)) AS [Cast] --Original 2 precision numeric