How does SQL Server know to retrieve these values this way?
Key someMoney
----------- ---------------------
1 5.00
2 5.002
3 5.0001
Basically, I'm wondering how to know how many decimal places there are without much of a performance hit.
I want to get
Key someMoney places
----------- --------------------- ----------
1 5.00 2
2 5.002 3
3 5.0001 4
The money data type has a fixed precision: with accuracy to a ten-thousandth of a monetary unit.
Money has 4 decimal places....it's a fixed-point data type.
Unlike the DECIMAL data type, the MONEY data type is always treated as a fixed-point decimal number. The database server defines the data type MONEY(p) as DECIMAL(p,2). If the precision and scale are not specified, the database server defines a MONEY column as DECIMAL(16,2).
If you need the highest precision, a DECIMAL can use up to 17 bytes for each value. Generally though, I like using DECIMAL(19,4) for currency, which needs 9 bytes and can store numbers 19 digits wide, where the last four digits are after the decimal place.
Money has 4 decimal places....it's a fixed-point data type.
This produces the correct results, but I'm not sure if it performs well enough for you and I haven't tried it with data other than the examples you listed:
;
with money_cte ([Key], [someMoney])
as
(
select 1, cast(5.00 as money)
union
select 2, cast(5.002 as money)
union
select 3, cast(5.0001 as money)
)
select [Key], [someMoney], abs(floor(log10([someMoney] - round([someMoney], 0, 1)))) as places
from money_cte
where [someMoney] - round([someMoney], 0, 1) <> 0
union
select [Key], [someMoney], 2 as places
from money_cte
where [someMoney] - round([someMoney], 0, 1) = 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With