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

岁酱吖の 提交于 2019-12-30 07:52:05

问题


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

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:


Have you tried:

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

This would return 2.55500000. Is that what you want?

UPDATE:

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

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

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




回答2:


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




回答3:


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

The default is: decimal(18,0)



来源:https://stackoverflow.com/questions/4169520/is-there-a-way-to-cast-float-as-a-decimal-without-rounding-and-preserving-its-pr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!