【问题标题】:SQL - Rounding a math expression [duplicate]SQL - 舍入数学表达式[重复]
【发布时间】:2021-12-21 15:48:50
【问题描述】:

我正在尝试将值四舍五入到小数点后两位。但是以下代码中的结果仍然显示 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

【问题讨论】:

  • 简化(你不应该需要 3 个表格来向我们展示你的舍入问题)-minimal reproducible example.
  • 您使用的是哪个 dbms?
  • @jarlh 使用 MSQL
  • else p.unitprice 可能是罪魁祸首。将其更改为else ROUND(p.unitprice,2)
  • @JamesKrueger 您的示例将 NewUnitPrice 显示为六位小数,而不是四位。你能澄清一下问题吗?

标签: sql sql-server tsql rounding


【解决方案1】:

解决方案是将数据类型更改为 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

【讨论】:

  • 最好将此问题标记为重复而不是回答它。 SO上有很多这样的问题。我们不需要再回答一个......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多