SQL 有没有办法将浮点数转换为小数而不舍入并保持其精度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4169520/
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 08:15:50  来源:igfitidea点击:

Is there a way to cast float as a decimal without rounding and preserving its precision?

sqlsql-servercasting

提问by Sonic Soul

So it appears that if you

所以看起来如果你

CAST(field1 as decimal) field1

this will automatically add rounding.

这将自动添加舍入。

The original is defined as:

原文定义为:

field1 type:float length:8 prec:53

field1 类型:浮点长度:8 prec:53

I need to cast it to decimal, because I need my Entity Framework layer to generate this field as decimal (instead of double).

我需要将它转换为十进制,因为我需要我的实体框架层将此字段生成为十进制(而不是双精度)。

Is there a way to cast it as decimal, so that it preserves original precision, and doesn't round?

有没有办法将它转换为十进制,以便它保留原始精度,而不是四舍五入?

I would like to avoid having to declare the precision in the cast, because:

我想避免在演员表中声明精度,因为:

  1. there are 100's of fields involved with varying precision, and;
  2. if the underlying table changes in the future, it could cause unforeseen bugs to emerge, and;
  3. makes the management more difficult.
  1. 有 100 个不同精度的领域,并且;
  2. 如果将来底层表发生变化,可能会导致出现不可预见的错误,并且;
  3. 使管理更加困难。

回答by Abe Miessler

Have you tried:

你有没有尝试过:

SELECT Cast( 2.555 as decimal(53,8))

This would return 2.55500000. Is that what you want?

这将返回2.55500000。那是你要的吗?

UPDATE:

更新:

Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:

显然,您还可以使用 SQL_VARIANT_PROPERTY 来查找值的精度和小数位数。例子:

SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')

returns 8|7

回报 8|7

You may be able to use this in your conversion process...

您可以在转换过程中使用它...

回答by Sadhir

Try SELECT CAST(field1 AS DECIMAL(10,2)) field1and replace 10,2with whatever precision you need.

尝试使用您需要的任何精度进行SELECT CAST(field1 AS DECIMAL(10,2)) field1替换10,2

回答by JeffO

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

默认为:十进制(18,0)