Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does SQL Server know what precision to use for money

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
like image 489
Daniel A. White Avatar asked Sep 01 '11 18:09

Daniel A. White


People also ask

What is the precision of money in SQL Server?

The money data type has a fixed precision: with accuracy to a ten-thousandth of a monetary unit.

How many decimal places is money in SQL?

Money has 4 decimal places....it's a fixed-point data type.

What data type should I use for money SQL?

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).

Which data type is best for currency amounts in SQL Server?

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.


2 Answers

Money has 4 decimal places....it's a fixed-point data type.

  • http://msdn.microsoft.com/en-us/library/ms179882.aspx
  • Is SQL Server 'MONEY' data type a decimal floating point or binary floating point?
like image 92
Chains Avatar answered Nov 15 '22 07:11

Chains


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
like image 30
Jeff Ogata Avatar answered Nov 15 '22 07:11

Jeff Ogata