Skip to content

Sequelize returns a string for decimal types #8019

Closed as not planned
Closed as not planned

Description

@raz3r

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.

app.get('/test/list/do', function(req, res) {
	models.test.findAll().then(function(tests) {
		res.json(tests);
	});
});

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.

Activity

  1. andrewmunro commented on Jul 27, 2017

    @andrewmunro

    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.

  2. andrewmunro commented on Jul 27, 2017

    @andrewmunro

    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?

  3. nerdlibfront commented on Jul 31, 2017

    @nerdlibfront

    Same here with the current releases of Sequelize (4.4.2) and mysql2 (1.3.6)

  4. nerdlibfront commented on Jul 31, 2017

    @nerdlibfront

    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.

  5. raz3r commented on Jul 31, 2017

    @raz3r
    Author

    Thank you, that solved my issue 👍

  6. andrewmunro commented on Jul 31, 2017

    @andrewmunro
  7. kingjerod commented on Feb 20, 2018

    @kingjerod

    Setting dialectOptions: { decimalNumbers: true } doesn't seem to work for Postgres. Is this a MySQL2 only option?

  8. deejbee commented on Apr 3, 2018

    @deejbee

    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?

  9. kingjerod commented on Apr 3, 2018

    @kingjerod

    @deejbee The solution I found:

    import * as pg from "pg";
    // setup your Sequelize instance
    pg.types.setTypeParser(1700, parseFloat);
    

    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.

  10. deejbee commented on Apr 3, 2018

    @deejbee

    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
    });
    
  11. kingjerod commented on Apr 3, 2018

    @kingjerod

    I also had to put it after my models are included (so basically final step). I'm using Sequelize version 4.26.

    const env = process.env;
    const modelPath = path.resolve(__dirname, "models");
    const sequelize = new Sequelize({
      name: env.POSTGRES_DB,
      host: env.POSTGRES_HOST,
      dialect: "postgres",
      username: env.POSTGRES_USER,
      password: env.POSTGRES_PASSWORD
    });
    sequelize.addModels([modelPath]);
    pg.types.setTypeParser(1700, parseFloat);
    
  12. deejbee commented on Apr 4, 2018

    @deejbee

    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.

  13. san02 commented on Apr 25, 2018

    @san02

    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.

  14. deejbee commented on Apr 25, 2018

    @deejbee

    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?)

  15. 46 remaining items

  16. added
    type: feature
    and removed
    status: understood
    type: other
    Great SSCCE
    on Apr 16, 2022
  17. ephys commented on Apr 16, 2022

    @ephys
    Member

    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

  18. ephys commented on Oct 6, 2022

    @ephys
    Member

    I'm closing in favor of #14296

  19. riosje commented on Oct 17, 2022

    @riosje

    For those who still arrives here looking for some solution and information as sequelize version "^6.3.5" this is still happening

    MYSQL SOLUTION

    If you're using MYSQL all what you need is specify this option in dialectOptions parameter:

    dialectOptions: { decimalNumbers: true }

    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.

    Suggested workaround

    sequelize.define("user", {
      foo: {
        type: Sequelize.DECIMAL,
        get() {
          // Workaround until sequelize issue #8019 is fixed
          const value = this.getDataValue('foo');
          return value === null ? null : parseFloat(value);
        }
      }
    });

    2. Modify the Sequelize datatype in the application bootstrap using a hook.

    const sequelize = new Sequelize(config.configPGSQL.database, config.configPGSQL.username, config.configPGSQL.password, {
      host: config.configPGSQL.host,
      dialect: config.configPGSQL.dialect,
      port: config.configPGSQL.port,
      logging: config.configPGSQL.logging,
      pool: config.configPGSQL.pool,
      dialectOptions: config.configPGSQL.dialectOptions,
      hooks: {
        beforeConnect() {
          console.log("beforeConnect");
          const cloneType = function (t, parseFn) {
            const clone = {};
            for (const name of Object.getOwnPropertyNames(t)) {
              clone[name] = t[name];
            }
            (clone.key = t.key), (clone.types = t.types), (clone.parse = parseFn);
            return clone;
          };
          const dTypes = {
            DECIMAL: cloneType(Sequelize.DataTypes.postgres.DECIMAL, parseFloat),
            INTEGER: cloneType(Sequelize.DataTypes.postgres.INTEGER, v => parseInt(v, 10)),
            BIGINT: cloneType(Sequelize.DataTypes.postgres.BIGINT, v => parseInt(v, 10)),
          };
          this.connectionManager.refreshTypeParser(dTypes);
        },
      },
    });

    hooks documentation

    Also highly suggest you to follow this issue -> #9074

  20. ephys commented on Oct 17, 2022

    @ephys
    Member

    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.

  21. riosje commented on Oct 17, 2022

    @riosje

    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

  22. ephys commented on Oct 17, 2022

    @ephys
    Member

    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 :)

  23. fenghourun commented on May 30, 2023

    @fenghourun

    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)

  24. ephys commented on May 31, 2023

    @ephys
    Member

    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)

  25. aboucodeur commented on Aug 15, 2023

    @aboucodeur

    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

  26. aboucodeur commented on Aug 15, 2023

    @aboucodeur

    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 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

existing workaroundtype: feature

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions