【问题标题】:Query number of decimal places in a sql server resultset查询 sql server 结果集中的小数位数
【发布时间】:2010-09-26 23:36:38
【问题描述】:

我有一个包含numeric(28,10) 类型字段的表。我想用等宽字体和匹配的小数位数显示记录,以便它们在右对齐时对齐。

有什么方法可以计算出在给定结果集中可以找到的最大小数位数,以便在显示每条记录时进行相应的格式化?

编辑:抱歉,我应该更清楚...如果结果集包含只有 3 位小数的数字,那么所有数字都应该只有 3 位小数(用零填充)。

【问题讨论】:

    标签: sql-server formatting decimal numeric


    【解决方案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
    

    所以问题是——你想做什么却没有给你想要的输出?

    【讨论】:

    • 对不起,我应该说清楚...如果我不需要,我不想一直精确到小数点后 10 位。一个更好的例子是 0.1, 0.12, 0.123 应该显示 0.100, 0.120, 0.123
    • @Joel Martinez:那你打算如何处理小数点后 10 位的数字?!
    • 如果结果集中有一个小数点后 10 位的数字,那么我希望将 所有行 显示为小数点后 10 位。我不想显示更多的小数位,而不是绝对必要的......但如果数据需要它,那么我会显示它们。我想这样做的原因是因为我希望用户能够扫描表格并快速比较数字。为此,必须排好小数位……不,我不想在单独的列中显示每个部分;-)
    • 所以查询需要知道基于最多的一个要显示多少精度?您保证对数据、SQL 或其他方式进行两次传递。我认为你最好显示小数点后十位,但祝你好运!
    • 好吧,很公平 :-) 我希望有人能提出一些我以前没有想到的明显解决方案,但看起来我无法避免这种情况。感谢您的验证!
    【解决方案2】:

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

    你可以

     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)
    

    如果由于某种原因选项 a) 不可接受,那么您将不得不这样做 b) 在程序上,无论是存储过程中的服务器端还是客户端程序中的客户端。

    【讨论】:

    • 是的,我试图避免使用字符串处理方法。不幸的是,按照您的建议,限制精度不是一种选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多