I have a database table with these two columns:
This table can store amounts in va
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
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
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:
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().
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
In SQL server you can :
select stuff(convert(varchar,amount) ,
len(convert(varchar,amount)) - DecimalPlaces - 1, 0, ".")