using Postgres 12.4 I found some inconsistencies rounding between float8 to decimal(24,8)
By doing
select
29314.630053404966::float8::decimal(24,8) as num1,
29314.630053404966::decimal(24,8) as num2
the return is:
num1: 29314.63005341 -> wrong
num2: 29314.63005340 -> correct
As you can see the rounding does not work properly
Any way to cast correctly from float8 to decimal(24,8)?
I would always use
decimalinstead of usingfloat8if I wanted to store decimal point values.why? there is an example
we can see the
0.1::float8 + 0.2::float8will get the wrong number.more detail can refer by What Every Programmer Should Know About Floating-Point Arithmetic
There is a way that might help you do that
we can try to cast the value as a string first, Before Casting
float8todecimal(24,8).This way might work, but that will cause performance issues.
sqlfiddle