Aram Boyajyan
Aram Boyajyan

Reputation: 844

MySQL cast as decimal not working as expected

This query:

SELECT CAST(30.123456789012345 AS DECIMAL(16,16))

Returns 0.9999999999999999.

Unless I got it completely wrong, it should return 30.1234567890123450.

Can anyone please explain what's going on?

Thanks!

Upvotes: 2

Views: 2851

Answers (2)

ulentini
ulentini

Reputation: 2412

DECIMAL(18, 16) should work. As you can read on MySQL manual:

The declaration syntax for a DECIMAL column is DECIMAL(M,D). The ranges of values for the arguments in MySQL 5.1 are as follows:

M is the maximum number of digits (the precision). It has a range of 1 to 65. (Older versions of MySQL permitted a range of 1 to 254.)

D is the number of digits to the right of the decimal point (the scale). It has a range of 0 to 30 and must be no larger than M.

So DECIMAL(16,16) tells MySQL to use all digits as decimal digits, without any integer part.

Upvotes: 2

Martin Smith
Martin Smith

Reputation: 454020

You would need DECIMAL(18,16).

16,16 reserves all 16 available digits of precision for values to the right of the decimal point.

Upvotes: 6

Related Questions