Question

I have below table structure and data :

create table sample
(
    id INT(10)
);

INSERT INTO sample
values
(23398),
(98743),
(54734);

Now I want to understand CAST function in mysql. Consider following query :

select 
cast((id/3) as decimal(2,2)) as cast1,
cast((id/3) as decimal(3,2)) as cast2,
cast((id/3) as decimal(4,2)) as cast3,
cast((id/3) as decimal(5,2)) as cast4,
cast((id/3) as decimal(6,2)) as cast5,
cast((id/3) as decimal(7,2)) as cast6,
id/3 as actualId
from sample;

Please see output of this query at SQL Fiddle.
I am wondering why this query gives 0.99, 9.99 and vice versa.
Can anyone explain it ?
Thanks in advance.

Was it helpful?

Solution

decimal is a type that takes 2 arguments

decimal(size, places) :

size determines how many digits are in the number.

places determines how many of those digits are to the right of the decimal.

decimal(2,2) - .00 - 2 digits both of which are to the right of the decimal

when casting (23398 / 3) = 7799.33333333 to declimal(2, 2) it yields a decimal in the specified amount of space closest to the desired number which is 0.99

decimal(3,2) - 0.00 - 3 digits 2 of which are to the right of the decimal

when casting (23398 / 3) = 7799.33333333 to declimal(3, 2) it yields a decimal in the specified amount of space closest to the desired number which is 9.99

if all of the original numbers were negative you would yield -0.99 and -9.99 because they are the closest numbers to the desired number within the allocated space

As a matter of fact java does something similar if you take the max double and try to convert it to an int you will give the max int which is no where near the max double

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