Domanda

I have two tables, invoice and invoice_items.

In invoice_items I have the columns:

  • quantity - INT
  • unit_price - DECIMAL(10,2)
  • discount - DECIMAL(10,2) - in percent

I was wondering whether or not it's neccessary to cast static values in the SQL as DECIMAL when calculating stuff, for example when finding the total price (with added VAT of 25%) of a line item:

SELECT (quantity * unit_price * (1 + discount/100)) * 1.25 AS item_price
FROM invoice_items

I.e. is it neccessary to cast 100, the result of (1 + discount/100) and 1.25 to DECIMAL to preserve precision or is this done internally?

È stato utile?

Soluzione

As suggested by Marcus Adams I avoided the need of decimal numbers by multiplying everything by 10^(number of decimals) = 10². This solution can - obviously - be applied to any similar problems where the maximum number of digits after the decimal point is known beforehand.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top