简体   繁体   English

SQL Server 2008:为什么这轮不能到两位小数?

[英]SQL Server 2008: Why won't this round to two decimal places?

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

The result I get looks like an integer 1,2 etc 我得到的结果看起来像整数1,2等

Try changing 16 to 16.0 尝试将16更改为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. 指定.0告诉sql server将其视为小数。

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

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. 由于您正在处理两个整数,因此SQL Server会截断余数,因此没有用于舍入的小数组件。

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 . 最简单的方法是将16改为16.0

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM