【问题标题】:Oracle SQL - How to display 2 decimal placesOracle SQL - 如何显示 2 位小数
【发布时间】:2021-07-19 13:48:45
【问题描述】:

帮我显示一个长度未知的数字,小数点后两位。 例子: 如果数字是 230000,那么我需要将其打印为 230000.00

我试过了

Select to_char(amount, 'FM99999999.90') as amt from customer;

【问题讨论】:

  • LPAD 和 RPAD 应该可以解决问题
  • 嵌套在to_number函数中似乎没有问题,推测是Oracle DB
  • 请添加相关RDBMS标签(MySQL,PostgreSQL,...)以获得相关解决方案。
  • 为什么不添加更多的 9?我厌倦了这个逻辑(check here),有了这个,你可以在表中插入“虚幻”大数字,仍然可以工作。

标签: sql oracle decimal number-formatting


【解决方案1】:

如下使用concat

select concat(amount, '.00') from customer

【讨论】:

    【解决方案2】:

    格式化通常是前端的“问题”;每个像样的工具(无论是 Oracle Apex、报告、表单、Jasper 报告……)都可以选择根据需要设置数字格式。为什么?以便这些值保持数字,以便能够应用,例如SUM 为他们提供功能或您可能需要的任何功能。

    在 SQL*Plus(或类似工具,甚至是 GUI 工具)中,格式化由 TO_CHAR 函数和所需的格式掩码完成。如果你想要两位小数和(例如)千位分隔符,你可以这样做:

    SQL> with customer (amount) as
      2    (select 230000 from dual union all
      3     select 3.14   from dual union all
      4     select 0.0002 from dual union all
      5     select 25.123 from dual
      6    )
      7  select amount,
      8         to_char(amount, 'fm999g999g990d00') new_amount,
      9    lpad(to_char(amount, 'fm999g999g990d00'), 10, ' ') new_amount2
     10  from customer;
    
        AMOUNT NEW_AMOUNT      NEW_AMOUNT2
    ---------- --------------- ----------------------------------------
        230000 230.000,00      230.000,00
          3,14 3,14                  3,14
         ,0002 0,00                  0,00
        25,123 25,12                25,12
    
    SQL>
    
    • 请注意,新值具有 ...0d00 格式掩码,可确保您实际上会在小数点周围看到
    • 使用GD 表示千组和小数,而不是逗号和点
    • new_amount2,另外,已应用 lpad,以便值右对齐。我假设这些值的最大长度是 10(你会知道的更好)

    如果您确实使用 SQL*Plus(现在很少见),您甚至可以使用它的 set numformat 命令 - 无需额外修改;你只需选择你所拥有的:

    SQL> set numformat 999g990d00
    SQL>
    SQL> with customer (amount) as
      2    (select 230000 from dual union all
      3     select 3.14   from dual union all
      4     select 0.0002 from dual union all
      5     select 25.123 from dual
      6    )
      7  select amount
      8  from customer;
    
         AMOUNT
    -----------
     230.000,00
           3,14
           0,00
          25,12
    
    SQL>
    

    【讨论】:

      猜你喜欢
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 2011-01-01
      • 1970-01-01
      相关资源
      最近更新 更多