Question

Just found out that this query:

SELECT 1 / 1000000;

will return 0, which is a small catastrophe for our economical program when doing vat calculations. How to set the default number of decimals without changing every query?

Edit

The example at hand is to get the vat part from a net value, with 6% vat. 6 / 106 = 0.056603773..., but SELECT 6 / 106 = 0.0566.

Was it helpful?

Solution

As documented under Arithmetic Operators:

In division performed with /, the scale of the result when using two exact-value operands is the scale of the first operand plus the value of the div_precision_increment system variable (which is 4 by default). For example, the result of the expression 5.05 / 0.014 has a scale of six decimal places (360.714286).

Therefore, either:

  • Increase div_precision_increment to suit your needs:

    SET div_precision_increment = 6;
    

    Or, to set globally (i.e. across all future sessions):

    SET GLOBAL div_precision_increment = 6;
    

    Or even set it in the [mysqld] section of your option file / on the command-line to ensure that it survives server restarts.

  • Explicitly cast the result of your operation to a type having your desired scale:

    SELECT CAST(1 / 1000000 AS DECIMAL(10,8));
    

OTHER TIPS

You can cast result to any data type. Below sql cast the result to decimal with precision 10.

select cast(1 / 1000000 as decimal(10,10));

EDIT: Result depends on your data types. Try this:

SELECT 6.000000 / 106.000000;

If your data is decimal with required precision then your result will be decimal with enough precision. So I think you should update date type in your database.

Try the net VAT on a ten thousand euro sale:

SELECT 10000 * (6/106)

I believe you will see the correct computation: 566.0377

If you want it displayed rounded to two decimal places, cents, do this:

SELECT ROUND(10000*(6/106),2)

You may want your currency (money) datatypes to be represented as DECIMAL. For example, a product unit price might be represented as

  DECIMAL(10,2) 

to allow dollars/pounds/euros and hundredths.

Then your arithmetic should not lose precision. For example,

 SELECT 24*(6/106)*CAST(1.20 AS DECIMAL(10,2))

will yield the 6% net VAT on two dozen items that cost 1.20 each.

To make this happen without mucking around with lots of queries, you may need to ALTER some of your columns' definitions.

I've tried this on MariaDB 10, MySQL 5.1, 5.5, and 5.6. It seems fine.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top