使用 sql 删除尾随零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14045994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 12:49:38  来源:igfitidea点击:

Remove trailing zeroes using sql

sqlsql-servertsql

提问by user1858332

Possible Duplicate:
Remove trailing zeros from decimal in SQL Server

可能的重复:
从 SQL Server 中的十进制中删除尾随零

I am trying to use the round function and not show any of the trailing zeroes but still getting some zeroes at the end. I am suppose to get 10.4 but getting something like this:

我正在尝试使用 round 函数而不显示任何尾随零,但最后仍然得到一些零。我想得到 10.4 但得到这样的东西:

10.400000

Here is my sql:

这是我的sql:

select round(AVG(CAST(k.TotalNumberDays AS numeric(12,2))),2) TotalNumber

How can i remove the trailing zeros here? I need to show only 10.4.

如何删除此处的尾随零?我只需要显示 10.4。

回答by Louis Ricci

You just have to cast it as a decimal(12,2).

您只需将其转换为小数(12,2)。

select cast(round(AVG(CAST(k.TotalNumberDays AS numeric(12,2))),2) as decimal(12,2)) TotalNumber

回答by Randy Minder

SQL Server supports formats float data type without trailing zeros, so you can remove trailing zeroes by casting the to a float. For example:

SQL Server 支持不带尾随零的浮点数据类型格式,因此您可以通过将 转换为浮点数来删除尾随零。例如:

Select Cast(10.40000 as float)

选择 Cast(10.40000 作为浮动)

This returns 10.4

这将返回 10.4

However, this is a presentation issue and really should be done in your presentation layer instead of wasting resources casting to different data types.

但是,这是一个表示问题,确实应该在您的表示层中完成,而不是浪费资源转换为不同的数据类型。

回答by infideltfo

Just move your CAST out of avg like here:

只需将您的 CAST 从 avg 中移出,如下所示:

select CAST(round(AVG(10.3543435),2) as numeric(12,1)) 

TotalNumber
---------------------------------------
10.4

(1 row(s) affected)

回答by C???

If I try this:

如果我试试这个:

SELECT(ROUND(CAST(10.4 AS numeric(12,2)), 2)

I get:

我得到:

10.40

If you use the numericor the decimaltypes, you will get up to as many zeros as you have set in the precision part of the data type.

如果您使用numericdecimal类型,您将获得与您在数据类型的精度部分设置的一样多的零。

In your example, you have specified 2 digits of precision, so you will always have up to 2 trailing zeros. Perhaps you need a different datatype, such as float.

在您的示例中,您指定了 2 位精度,因此您将始终有最多 2 个尾随零。也许您需要不同的数据类型,例如float.