Formatting an SQL numeric query result with an arbitrary number of decimal places

后端 未结 6 366
孤街浪徒
孤街浪徒 2021-01-15 04:51

I have a database table with these two columns:

  • Amount: numeric (18,0)
  • DecimalPlaces: numeric (18,0)

This table can store amounts in va

相关标签:
6条回答
  • 2021-01-15 05:21

    How about?

    select 12345 amount, 2 decimalPlaces, substr( to_char( 12345 ), 1, length (to_char( 12345 ) ) - 2 ) || '.' || substr( to_char( 12345 ), -2 ) result from dual /

         amount decimalPlaces result
     ---------- ------------- ------
         12345              2 123.45
    
    0 讨论(0)
  • 2021-01-15 05:22

    Martlark's answer for Oracle led me to this solution for SQL Server:

    select
      left(cast(Amount as varchar), len(cast(Amount as varchar)) - DecimalPlaces) +
      left('.', DecimalPlaces) +
      right(cast(OriginalCurrencyAmount as varchar), DecimalPlaces
    ) as FormattedAmount
    from MyTable
    
    0 讨论(0)
  • 2021-01-15 05:24

    The best I've been able to come up with so far is:

    select Amount/power(10, DecimalPlaces) from MyTable
    

    But it doesn't do exactly what I want:

    • Oracle: the trailing zeroes are stripped, so US$15.00 looks like "15", not "15.00"
    • SQL Server: a whole lot of extra trailing zeroes are added, so $23.99 looks like "23.99000000000" instead of "23.99"
    0 讨论(0)
  • 2021-01-15 05:33

    Your problem is that there isn't an easy way to do this for both SQLServer and Oracle in one query.

    The Correct way to do this for SQLServer is to use STR:

    Select STR(Amount, 18, DecimalPlaces) from myTable;
    

    The correct way to do this for Oracle is using to_char:

    SELECT to_char (amount, '99999999999999.'||rpad('',DecimalPlaces, '0')) 
    from MyTable;
    

    The queries presented by jms and Andrew won't work in an Oracle query because Oracle SQL uses LENGTH() not LEN(). And Oracle uses to_char() not Cast().

    0 讨论(0)
  • 2021-01-15 05:38

    This is gross but worked for the current inputs on SQL server.

    select 
        substring(
         CAST(
          CAST(
            (amount *  power(-0.100000000000000000,decimalPlaces*1.000000000000000000)) as numeric(36,18)
          )as varchar(30)
         )
        ,1,len(cast(amount as varchar(20))) + (CASE WHEN decimalPlaces = 0 THEN 0 ELSE 1 END )) 
    
    from
     myTable
    
    0 讨论(0)
  • 2021-01-15 05:40

    In SQL server you can :

    select stuff(convert(varchar,amount) ,
             len(convert(varchar,amount)) - DecimalPlaces - 1, 0, ".")
    
    0 讨论(0)
提交回复
热议问题