2010-09-26 111 views
1

我有一个包含numeric(28,10)类型字段的表。我希望以等宽字体显示记录,并显示匹配的小数位数,以便在右对齐时排列。查询sql服务器结果集中的小数位数

是否有任何方法可以找出在给定结果集中可以找到的最大小数位数,以便我可以根据显示每条记录的格式进行相应的格式化?

编辑:对不起,我应该已经更清楚了...如果结果集包含只有3位小数的数字,那么所有的数字应该只有3位小数(用零填充)。

回答

1

的等宽字体完全是一个演示问题...

我没有看到你的右对齐需要当我测试:

CREATE TABLE [dbo].[Table_1](
    [num] [numeric](28, 10) NOT NULL 
) 

INSERT INTO [example].[dbo].[Table_1] VALUES (1.1234567890); 
INSERT INTO [example].[dbo].[Table_1] VALUES (1.123456789); 
INSERT INTO [example].[dbo].[Table_1] VALUES (1.1234567); 

SELECT [num] 
    FROM [example].[dbo].[Table_1] 

...的回报:

num 
--------------- 
1.1234567890 
1.1234567890 
1.1234567000 

所以问题是 - 你想做什么,是不是给你你想要的输出?

+0

对不起,我应该已经清楚了......如果我不需要,我不想一直走到小数点后10位。一个更好的例子是0.1,0.12,0.123应该显示0.100,0.120,0.1123 – 2010-09-27 00:20:55

+0

@Joel Martinez:那么你打算如何处理有10位小数的数字?! – 2010-09-27 00:22:56

+0

如果结果集中有一个有10位小数的数字,那么我希望将*所有行*显示为10位小数。我想显示没有更多的小数位数是绝对必要的......但如果数据有必要,那么我会显示它们。我想这样做的原因是因为我希望用户能够扫描表格并快速比较数字。要做到这一点小数位必须排队......并且我不想在单独的列中显示每个部分;-) – 2010-09-27 02:25:26

0

您想在哪里显示结果?查询分析器?在应用程序中?

您可以

a) format the column to have a 
    finite number (known in advance) of 
    digits to the right of the decimal 
    point, truncating at that position; 
    this is the typical practice or 

b) read through all of the rows in the 
    resultset to determine the value 
    with the greatest number of digits 
    to the right of the decimal point 
    (casting to string, splitting the 
    value using the decimal point as 
    delimiter, and getting the length of 
    the decimal-fraction string) 

如果由于某种原因选项)是不可接受的,那么你就必须要这么做二)程序上,无论是服务器端,在客户端程序中的存储过程或客户端。

+0

是的,我试图避免字符串处理方法。不幸的是,如您所建议的那样限制精度不是一种选择。 – 2010-09-27 00:19:57