You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Sequelize returns a string for decimal types #8019
I have a simple model with a DECIMAL column. Whenever I query that model the column is returned as a string rather than a float. Thing is, I am not sure whether the issue is on ExpressJS side (res.json()) or on Sequelize side. Or maybe there's something else I am not aware of.
I am using the latest version of Sequelize and ExpressJS along with MySQL 5.7.
EDIT: I tried logging the model directly in Node and the field was already converted to a string before sending it out. So it must be Sequelize.
I understand it's probably due to precision issues but I would like to know if there's a away to get a number regardless.
Reacted by Nick Laros, Karl Adler, David Alejandro Cardenas Gonzalez, Duy Nguyen, Indospace.io, Cez V, gunar, Oleg Derecha, Ratul sharker, Yota Toyama and 37 more
Seems like upgrading from 3.30.4 to 4.0.0 caused this. Either something in the sequelize 4.0 release or possibly due to switching the dependency from mysql to mysql2?
This is an issue with mysql2 returning decimals as a string to preserve precision: #7465
If you are sure that your data won't run into precision issues you can set dialectOptions: { decimalNumbers: true }
when instantiating sequelize to get the previous behavior.
Worked for my case.
Reacted by Eric S. Rogstad, David Lung, matrixbirds, FujiBilly, sky91.cn, Thiago Sciotta, Alex, ǝᴉsɹnoɥʇ sɐuoɾ, Fernando Perez, Tomer and 65 more
Reacted by Benjamin GARDIEN, Pietro Bonaccorso, Victor Barros, Mitchell Sion, Ali Garajian, Godswill Edet, aoriekhov-godaddy, Andrii Oriekhov and Maverick Wolfe
Reacted by richarepo, Soon Sam Ribeiro Santos, Yatish Motamarri, Manoj Singh Negi, Benjamin GARDIEN, Ruofan Wei, Diego, Brandon Castillo, Godswill Edet, Andrii Oriekhov and 1 more
Setting dialectOptions: { decimalNumbers: true } doesn't seem to work for Postgres. Is this a MySQL2 only option?
Reacted by Ben Tedder, Nicolas Schönborn, Kosteg, Hiswe, Greg, Vladyslav, Sergey Peshkov, Chrysanthos Spiliotopoulos, Karl Adler, Giovane de Oliveira and 41 more
This is breaking when using the postgres driver too as @kingjerod has suggested. I'm trying to migrate from using mssql to postgres and this is causing a massive headache since I use decimals all over the place. The solution can't surely be to parse every string as decimal that comes back? Should this be re-opened or have I missed something?
Thanks for the the quick reply @kiddouk. I'm not too sure where that code should go though. I tried it before and after this and several other places but it didn't effect the result so not sure what I'm missing :
var sequelize = new Sequelize({
host: 'localhost',
..etc
});
I was using PostgreSQL and Sequelize 4.33.4 . these fixing listed above did not work for me. Then I downgraded the sequelize version to 4.26.0 . by using pg.types.setTypeParser(1700, parseFloat);
, this issue got fixed. Thanks to @kingjerod . But I am afraid, I may find some other bugs in future, since my entire project I worked was with Sequelize 4.33.4 . I would really appreciate if someone can suggest a solution to solve this issue for sequelize versions 4.33. or later (latest to be 4.37) where pg dependency seems to have removed as @deejbee said.
I finally found a way and ended up doing this with the latest (4.37.6)
Sequelize.postgres.DECIMAL.parse = function (value) { return parseFloat(value); };
using setTypeParser() had no effect.
Since I know all my values are currency style decimals there hopefully won't be a problem losing any precision. I wish there was a different type of DECIMAL (DECIMAL_2 or DECIMAL_INSECURE perhaps?)
Reacted by Chrysanthos Spiliotopoulos, lblazecki, Robin Pham, anna, Justin Vencel, Iskandar Zulkarnain, !opips, Felipe Valtl de Mello, madmoizo, Alexandre-Jacques St-Jacques and 46 more
Reacted by Alyx
Reacted by LoginPassword
Reacted by Marko Kosir, Amin Ariana, Jake Cukjati, Kevin Ashcraft, Anthony DOWTK, Rodrigo Cipriani da Rosa, Jinawong, Luque, KMA, Tobias Løfgren and 4 more
Reacted by Jake Cukjati, Anthony DOWTK, Rodrigo Cipriani da Rosa, Tobias Løfgren, developerrowan, Ahmed Hadjou, Ruofan Wei, Rafael Cerri, Senduran Ravikumar, Guilherme Faga and 2 more
Reacted by Limomx, Jake Cukjati, Rodrigo Cipriani da Rosa, richarepo, Tobias Løfgren and dyktek
Removing the breaking change label because DataTypes.DECIMAL will continue returning strings by default but we plan on letting you choose to unsafely cast it to number if you choose to with #14296
Keep in mind that number is not capable of safely representing DECIMAL or BIGINT (which is why we won't enable this by default). Another way of fixing your issue is to use DataTypes.INTEGER and DataTypes.DOUBLE instead.
Hi @ephys thanks for comment on this and all the effort you put on this awesome project.
as far as I can see there is a lot of confusion over this topic, but here my comments:
your suggestion of use DOUBLE instead of DECIMAL works pretty well, sequelize returns the data type as expected (number), this works while you don't need a fixed decimal LENGTH.
for example this approach DataTypes.DOUBLE(18,4) PostgresSQL does not support 'DOUBLE PRECISION' with LENGTH, there is where the DECIMAL data type becomes important.
There is multiple discussions on stack over flow where encourage people not to use FLOAT for financial operations, instead of that they suggest the usage of DECIMAL data types.
Maybe all of us who ended up here in this issue trying to bring support to DECIMAL data type on sequelize, have a wrong design of the software or perhaps we have misunderstanding of programming data structures.
Anyway, thank you again @ephys for taking the time and document all those workarounds and POCs, even to answer all those issue comments
What you said about numeric amounts is exactly what I mean :) you should not use float or double to store numeric amounts, but the JavaScript number type is a double (both the SQL double, float, and real, as well as the JS number type are IEEE 754 floating point numbers).
You definitely should use either integers or decimals for that. But representing decimals using the JS number type will lead to the same imprecision issues as if you stored them as doubles in the database.
JavaScript doesn't have a decimal type (yet), so we return them as strings to prevent any loss of precision. You can then use libraries like bigdecimal to handle them
Similarly, not all bigints values can be represented by the JS number type. Which is why for now they're returned as strings too. Now that JS does support a bigint type (1n), we're planning on returning them as js bigints instead (in the next major release)
Of course you're free to use the JS number type, which is why we'd like to add a flag you can turn on. But we'll make it opt-in instead of the default :)
Reacted by Jefferson, Abdulsamad Suleiman and David Feng
Reacted by Abdulsamad Suleiman and Haritha Weerathunga
Keep in mind that number is not capable of safely representing DECIMAL or BIGINT (which is why we won't enable this by default). Another way of fixing your issue is to use DataTypes.INTEGER and DataTypes.DOUBLE instead.
Does this mean that using DataType.DOUBLE is supposed to give number at runtime? I'm running into the same issue (getting a string) when using DataType.DOUBLE (i'm using sequelize-typescript)
Yes DataType.DOUBLE should produce a number. If you're getting a string, there might be a bug (In which case I encourage you to open a new bug report with a reproducible example if you can)
Supprimer l' breaking changeétiquette car DataTypes.DECIMALdiffusée à renvoyer des chaînes par défaut, mais nous prévoyons de vous laisser choisir de le convertir de manière non sécurisée en nombre si vous le souhaitez avec # 14296
C'ets dangereux pouvoir gerer le types soit surtout avec des valeurs monetaires qui est le nerd de la geurre des developpeur LE DECIMAL de sequeelize => NUMERIC a postgresql . Donner le choix peut jouer sur #performances
I build a saas stock management app i'm very fan of postgresql example :
compte.solde+=20000.88// client side float (like react)// DataTypes.DECIMAL(val,len) like string// bug is : 60002.6720000.89// Solution just using parser and typeof() to know types
Activity
andrewmunro commentedon Jul 27, 2017
I have just updated to the latest version of sequelize and started having the same issue. It's returning strings for my decimal data types.
andrewmunro commentedon Jul 27, 2017
Seems like upgrading from 3.30.4 to 4.0.0 caused this. Either something in the sequelize 4.0 release or possibly due to switching the dependency from mysql to mysql2?
nerdlibfront commentedon Jul 31, 2017
Same here with the current releases of Sequelize (4.4.2) and mysql2 (1.3.6)
nerdlibfront commentedon Jul 31, 2017
This is an issue with mysql2 returning decimals as a string to preserve precision:
#7465
If you are sure that your data won't run into precision issues you can set
dialectOptions: { decimalNumbers: true }when instantiating sequelize to get the previous behavior.
Worked for my case.
raz3r commentedon Jul 31, 2017
Thank you, that solved my issue 👍
andrewmunro commentedon Jul 31, 2017
Fixed for me too. Suggest this workaround is added to here http://docs.sequelizejs.com/manual/tutorial/upgrade-to-v4.html
kingjerod commentedon Feb 20, 2018
Setting
dialectOptions: { decimalNumbers: true }doesn't seem to work for Postgres. Is this a MySQL2 only option?deejbee commentedon Apr 3, 2018
This is breaking when using the postgres driver too as @kingjerod has suggested. I'm trying to migrate from using mssql to postgres and this is causing a massive headache since I use decimals all over the place. The solution can't surely be to parse every string as decimal that comes back? Should this be re-opened or have I missed something?
kingjerod commentedon Apr 3, 2018
@deejbee The solution I found:
1700 corresponds to the Decimal type. Using parseFloat like this is only safe if you know your numbers will be within the valid float range.
deejbee commentedon Apr 3, 2018
Thanks for the the quick reply @kiddouk. I'm not too sure where that code should go though. I tried it before and after this and several other places but it didn't effect the result so not sure what I'm missing :
kingjerod commentedon Apr 3, 2018
I also had to put it after my models are included (so basically final step). I'm using Sequelize version 4.26.
deejbee commentedon Apr 4, 2018
Ah, I'm using 4.37.4 and the fix no longer works. Am now going through the changes to see why...
Update 1: 4.32.5 removed the dependency on pg-types package and it looks like the fix fails after that for some reason.
san02 commentedon Apr 25, 2018
I was using PostgreSQL and Sequelize 4.33.4 . these fixing listed above did not work for me. Then I downgraded the sequelize version to 4.26.0 . by using pg.types.setTypeParser(1700, parseFloat);
, this issue got fixed. Thanks to @kingjerod . But I am afraid, I may find some other bugs in future, since my entire project I worked was with Sequelize 4.33.4 . I would really appreciate if someone can suggest a solution to solve this issue for sequelize versions 4.33. or later (latest to be 4.37) where pg dependency seems to have removed as @deejbee said.
deejbee commentedon Apr 25, 2018
I finally found a way and ended up doing this with the latest (4.37.6)
Sequelize.postgres.DECIMAL.parse = function (value) { return parseFloat(value); };using setTypeParser() had no effect.
Since I know all my values are currency style decimals there hopefully won't be a problem losing any precision. I wish there was a different type of DECIMAL (DECIMAL_2 or DECIMAL_INSECURE perhaps?)
46 remaining items
ephys commentedon Apr 16, 2022
Removing the
breaking changelabel becauseDataTypes.DECIMALwill continue returning strings by default but we plan on letting you choose to unsafely cast it to number if you choose to with #14296ephys commentedon Oct 6, 2022
I'm closing in favor of #14296
riosje commentedon Oct 17, 2022
For those who still arrives here looking for some solution and information as sequelize version
"^6.3.5"this is still happeningMYSQL SOLUTION
If you're using MYSQL all what you need is specify this option in
dialectOptionsparameter:you can find more information here in the API documentation
Postgresql SOLUTION
The above solution doesn't work with Postgresql so far you have 2 options to workaround this:
1. Creeate a getter function within each field on every model.
2. Modify the Sequelize datatype in the application bootstrap using a hook.
hooks documentation
Also highly suggest you to follow this issue -> #9074
ephys commentedon Oct 17, 2022
Keep in mind that
numberis not capable of safely representingDECIMALorBIGINT(which is why we won't enable this by default). Another way of fixing your issue is to useDataTypes.INTEGERandDataTypes.DOUBLEinstead.riosje commentedon Oct 17, 2022
Hi @ephys thanks for comment on this and all the effort you put on this awesome project.
as far as I can see there is a lot of confusion over this topic, but here my comments:
your suggestion of use DOUBLE instead of DECIMAL works pretty well, sequelize returns the data type as expected (number), this works while you don't need a fixed decimal LENGTH.
for example this approach
DataTypes.DOUBLE(18,4)PostgresSQL does not support 'DOUBLE PRECISION' with LENGTH, there is where the DECIMAL data type becomes important.There is multiple discussions on stack over flow where encourage people not to use FLOAT for financial operations, instead of that they suggest the usage of DECIMAL data types.
Maybe all of us who ended up here in this issue trying to bring support to DECIMAL data type on sequelize, have a wrong design of the software or perhaps we have misunderstanding of programming data structures.
Anyway, thank you again @ephys for taking the time and document all those workarounds and POCs, even to answer all those issue comments
ephys commentedon Oct 17, 2022
What you said about numeric amounts is exactly what I mean :) you should not use float or double to store numeric amounts, but the JavaScript number type is a double (both the SQL double, float, and real, as well as the JS number type are IEEE 754 floating point numbers).
You definitely should use either integers or decimals for that. But representing decimals using the JS number type will lead to the same imprecision issues as if you stored them as doubles in the database.
JavaScript doesn't have a decimal type (yet), so we return them as strings to prevent any loss of precision. You can then use libraries like bigdecimal to handle them
Similarly, not all bigints values can be represented by the JS number type. Which is why for now they're returned as strings too. Now that JS does support a bigint type (
1n), we're planning on returning them as js bigints instead (in the next major release)Of course you're free to use the JS number type, which is why we'd like to add a flag you can turn on. But we'll make it opt-in instead of the default :)
fenghourun commentedon May 30, 2023
Does this mean that using
DataType.DOUBLEis supposed to givenumberat runtime? I'm running into the same issue (getting a string) when usingDataType.DOUBLE(i'm using sequelize-typescript)ephys commentedon May 31, 2023
Yes
DataType.DOUBLEshould produce anumber. If you're getting a string, there might be a bug (In which case I encourage you to open a new bug report with a reproducible example if you can)aboucodeur commentedon Aug 15, 2023
C'ets dangereux pouvoir gerer le types soit surtout avec des valeurs monetaires qui est le nerd de la geurre des developpeur LE DECIMAL de sequeelize => NUMERIC a postgresql . Donner le choix peut jouer sur #performances
aboucodeur commentedon Aug 15, 2023
I build a saas stock management app i'm very fan of postgresql example :