在 SQL Server 2008 中将浮点数转换为十进制数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4186789/
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
Converting float to decimal in SQL Server 2008
提问by Sonic Soul
I have a view which needs to return type decimal for columns stored as float.
我有一个视图需要为存储为浮点数的列返回十进制类型。
I can cast each column to decimal as follows:
我可以将每一列转换为十进制,如下所示:
, CAST(Field1 as decimal) Field1
The problem with this approach, is that decimal defaults to 18,0, which automatically rounds the float columns to 0. I would like to keep a precision of up to 12 decimal places.
这种方法的问题是小数默认为 18,0,它会自动将浮点列四舍五入为 0。我想保持最多 12 位小数的精度。
However, if I do this:
但是,如果我这样做:
, CAST(Field1 as decimal(12,12)) Field1
I get a runtime error:
我收到一个运行时错误:
"Arithmetic overflow error converting float to data type numeric"
the float column is defined as length: 8 Precision: 53in the table. I can not modify anything about the table.
浮点列定义为长度:8 精度:表中的53。我无法修改有关表格的任何内容。
What's the proper way to cast it as decimal w/out losing decimal precision?
将其转换为十进制而不丢失小数精度的正确方法是什么?
回答by Quassnoi
12, 12
means no digits before the decimal separator: 12
digits in total, 12
of them being after the period.
12, 12
表示小数点分隔符之前没有数字:12
总共数字,12
其中在句点之后。
Use a more appropriate range, say:
使用更合适的范围,例如:
DECLARE @var FLOAT = 100
SELECT CAST(@var as decimal(20,12))
which gives you 8
digits before the separator, or adjust it as needed.
它8
在分隔符之前为您提供数字,或根据需要进行调整。