SQL Server 2008:为什么不四舍五入到小数点后两位?

发布于 2024-10-16 10:12:09 字数 119 浏览 2 评论 0原文

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

我得到的结果看起来像整数 1,2 等

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

The result I get looks like an integer 1,2 etc

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

暖树树初阳… 2024-10-23 10:12:09

尝试将 16 更改为 16.0

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

您会看到奇怪的结果,因为它将除法结果视为整数而不是小数。指定 .0 告诉 sql server 将其视为十进制。

更新:

如果尾随零让你感到害怕,你可以随时这样做:

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

Try changing 16 to 16.0

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

You are seeing strange results because it is treating the results of your division as an integer rather than a decimal. Specifying the .0 tells sql server to treat it as a decimal.

UPDATE:

If the trailing zero's are freaking you out you can always do this:

SELECT
   CAST(ROUND(WeightInOZ / 16.0, 2) AS NUMERIC(8,2)) as WeightInLbs
FROM
   Inventory
婴鹅 2024-10-23 10:12:09

问题是这样的:

WeightInOZ / 16

由于您正在处理两个整数,SQL Server 会截断余数,因此没有小数部分可供舍入。

您想要做的是强制它执行浮点(或十进制)除法。最简单的方法是将 16 更改为 16.0

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

The problem is this:

WeightInOZ / 16

Since you're dealing with two integers, SQL Server truncates the remainder, so by there's no fractional component for it to round.

What you want to do is force it to perform floating-point (or decimal) division. The easiest way would be to change 16 to 16.0.

SELECT
   ROUND(WeightInOZ / 16.0, 2)as WeightInLbs
FROM
   Inventory
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文