Skip to content

Npgsql returns additional “0” decimals after all numeric values #1466

Closed

Description

@jbourne2

Post originaly posted on Stackoverflow : http://stackoverflow.com/questions/42539513/npgsql-returns-additional-0-decimals-after-all-numeric-values

Reply from @roji asking to open issue in Github : "Thank you. This actually seems to be a problem in Npgsql's numeric type handler... Can you please open an issue at github.com/npgsql/npgsql? As a workaround you can use Math.Round to enforce precision on the client side. – Shay Rojansky "


Complete repost below :

We recently upgraded our Npgsql library from (very old) 2.0.11.91 to latest build 3.2.1.

In Npgsql 2, all numeric values returned (either using NpgsqlDataAdapter, NpgsqlDataReader, etc) would have the precision and scale of the datatype in the query (or in the Postgres table if not specifically set in the query). For example:

string sql_query = "SELECT 2.33::numeric(38,2)" would return 2.33

In Npgsql 3 however, all numeric values with decimals are now returned (either using NpgsqlDataAdapter, NpgsqlDataReader, etc) with additional unnecessary decimals (total count of decimals always = 4), despite precision & scale being set in the query (or in the Postgres table). For example:

string query = "SELECT 2.33::numeric(38,2)" now returns 2.3300

string query= "SELECT 2.3::numeric(38,1)" now returns 2.3000

Code extract with NpgsqlDataAdapter to DataGridView:


NpgsqlConnection conn = new NpgsqlConnection("all_required_paramaters");
conn.Open();

DataSet ds = new DataSet();
DataTable dt = new DataTable();

string sql = "SELECT date , numeric_data1, numeric_data2 , numeric_data3 
FROM any_table order by date desc ";

NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
ds.Reset();
da.Fill(ds);
dt = ds.Tables[0];
dataGridView_ABC.DataSource = dt;

conn.Close();

Code extract with NpgsqlDataReader

NpgsqlConnection conn = new NpgsqlConnection("all_required_paramaters");

conn.Open();

string sql = "SELECT date , numeric_data1, numeric_data2 , numeric_data3 
FROM any_table order by date desc ";

NpgsqlCommand cmd = new NpgsqlCommand(sql, conn);
Npgsql.NpgsqlDataReader res = cmd.ExecuteReader();

List<string> _data1 = new List<string>();
List<string> _data2 = new List<string>();
List<string> _data3 = new List<string>();

while (res.Read())
{
_data1.Add(res["numeric_data1"].ToString());
_data2.Add(res["numeric_data2"].ToString());
_data3.Add(res["numeric_data3"].ToString());
}

conn.Close();
res.Close();

Only exception to this is when values don't have any decimal, they are correctly be returned, for example:

 string query= "SELECT 2::numeric(38,0)" does correctly returns 2

Question : How can we make Npgsql 3.2.1 return the precision and scale of the data type & length in the query or in the Postgres table (i.e. without all unnecessary additional decimals) as it was done by default in Npgsql 2?

Thank you very much.

Activity

  1. roji commented on Mar 1, 2017

    @roji
    Member

    The problem is that in the Npgsql type handler for numeric, the dscale component (fourth component of the header) is totally ignored/

    Relevant SO: http://stackoverflow.com/questions/1132765/adjusting-decimal-precision-net

    @Emill, I think you wrote the numeric handler... What do you think about this? I'm not good enough with floating point to be certain. We can do Math.Round() inside the type handler, but that may be bad for efficiency. It may make sense not to take care of this and leave it to the user, I'm not sure.

  2. Emill commented on Mar 1, 2017

    @Emill
    Contributor

    What happens if you execute string query = "SELECT 2.33::numeric" and string query = "SELECT 2.33::numeric(38,2)::text"? (Sorry I don't have the environment set up right now to execute that myself)

  3. roji commented on Mar 1, 2017

    @roji
    Member

    I get 2.33 for both in psql, but 2.3300/2.33 via Npgsql.

  4. jbourne2 commented on Mar 1, 2017

    @jbourne2
    Author

    I get via Npgsql :
    string query = "SELECT 2.33::numeric" returns 2.3300
    string query = "SELECT 2.33::numeric(38,2)::text" returns 2.33

  5. roji commented on Mar 1, 2017

    @roji
    Member

    Apologies, I misunderstood above (ran the two queries in psql). Corrected this.

    I'm still not 100% sure we have to correct this on our side - I think ignoring dscale has no effect on calculation, only on display when doing ToString(), and I'd like to avoid the overhead of Math.Round() or similar. On the other hand PostgreSQL does transmit the dscale...

  6. Emill commented on Mar 1, 2017

    @Emill
    Contributor

    I'm pretty sure I simply didn't do anything special to be able to preserve the dscale when converting to decimal, as described in http://stackoverflow.com/questions/1132765/adjusting-decimal-precision-net. Postgresql internally represents a numeric as a sequence of 4 decimal digits, that's why the number of decimals is a multiple of 4.

    The Npgsql code can of course be enhanced.

  7. roji commented on Mar 1, 2017

    @roji
    Member

    Feel like taking a look? You're the one who knows best that part

  8. Emill commented on Mar 1, 2017

    @Emill
    Contributor

    Maybe in a week or so. Have to much other stuff to do...

  9. roji commented on Mar 1, 2017

    @roji
    Member

    OK, take your time :)

  10. jbourne2 commented on Mar 1, 2017

    @jbourne2
    Author

    Thank you gentlemen; we appreciate it.

  11. jbourne2 commented on Mar 29, 2017

    @jbourne2
    Author

    Hi @roji and @Emill , Quick follow up on this. Any development? Thank you very much.

  12. roji commented on Apr 2, 2017

    @roji
    Member

    I'm definitely not going to have any time to look at this anytime soon, @Emill take a look if you feel like it.

  13. influento commented on Apr 12, 2017

    @influento

    Hello. We stucked on this issue in our project too. Hope it will be solved, because we love npgsql

  14. roji commented on Apr 12, 2017

    @roji
    Member

    For anyone stuck on this, you can always work around it yourself (e.g. with Math.Round).

  15. influento commented on Apr 13, 2017

    @influento

    The thing is we are using Dapper (for object mapping), so we are avoiding direct work with the data, which we're recieving from db. Interesting, that when I tried to recieve dynamic object via Dapper I had my Numeric values as objects and when I've converted them to decimal I didn't have any problems (I recieved correct values, not 0). But if we are trying to recieve not dynamic result (concrete object) we're getting 0.

  16. StillLearnin commented on May 16, 2017

    @StillLearnin
    Contributor

    For anyone stuck on this, you can always work around it yourself (e.g. with Math.Round).

    @roji This is a nice idea but doesn't work in our case.

    We have varying lengths of decimals such as 0.36, 0.0599, 0.177450 in a numeric column. Because this is a legacy application, we cannot force the field to a specific length and the data is handled differently depending on the number of decimal places.

    NpgsqlDataReader GetDecimal returns 0.36 and 0.0599 correctly but returns 0.177450 as 0.17745000. Since what's in the database and what we get from GetDecimal aren't consistent, we can't know what the correct rounding should be. In calculations this wouldn't make any difference but like I said, the code being executed is based on the number of decimal places.

    To me it seems like a bug if we can't count on getting exactly what is in the database.

  17. StillLearnin commented on May 16, 2017

    @StillLearnin
    Contributor

    GetValue and GetString also return 0.017745000

  18. roji commented on May 17, 2017

    @roji
    Member

    To be clear, I agree that this is an issue that needs to be fixed - Math.Round() was only a suggestion until we do so. @Emill, think you'll have time to look at this?

  19. DoraemonDesu commented on Jul 18, 2017

    @DoraemonDesu
    Contributor

    Hello @roji and @jbourne2

    Evidences are found regarding this bug:

    • As reported, if data is handled by NumericHandler, sometimes it has trailing zeros. We found a "4-digit" pattern related to this issue, for example:
      0.1			returned as		0.1000
      0.01			returned as		0.0100
      0.001			returned as		0.0010
      0.0001			returned as		0.0001
      0.00001			returned as		0.00001000
      0.000000001		returned as 		0.000000001000
      
    • The numeric handler will open 4-digit, every "group number". This is caused by design.
      • The NumericHandler reads from buffer then constructs the decimal everytime method Read() is called
      • The NumericHandler groups the digit and multiply them by a weight then and add them, for example:
        0.01 // has one group (open 4 spaces)
        0100 × 0.0001 = 0.0100
        
        0.00001 // has two groups (open 8 spaces)
        (0000 × 0.0001) + (1000 × 0.00000001) = 0.00001000
    • Mathematically and programatically 0.1 is the same as 0.1000, because:
      if (0.1M == 0.1000M){...} // yields true
    • Even tough it is the same, if we decode the decimal variable into 4 × 32-bit integers (using Decimal.GetBits()), the values are different. Because:
      0.1 		equals	1 × 10^-1		(96-bit value will store 1)
      0.1000		equals	1000 × 10^-4		(96-bit value will store 1000) // because it is not at its most simplified form
      
    • Plus, if converted to string, value is not equal anymore.

    Solutions

    • Normalize value to remove trailing zero in NumericHandler before the value is returned (We will pull request on this issue).
    • Or reduce the weight of each loop (More loop will be needed to construct the value).

    Results

    • 2 files were changed for this fix.
      • src/Npgsql/TypeHandlers/NumericHandlers/NumericHandler.cs
      • test/Npgsql.Tests/BugTests.cs
    • In NumericHandlers, the result is normalized before returned.
    • A new test method is added to the BugTests.cs, this will compare if value returned from PostgreSQL is the same as original after the values are decoded.
      • Npgsql without this fix will not pass the new test
      • Npgsql with this fix has passed the new test

    Conclusion:

    • This issue can be fixed on client app.
    • But also can be fixed on Npgsql (only takes one line). We think it is better to return the value without trailing zero.
  20. roji commented on Jul 18, 2017

    @roji
    Member

    @DoraemonDesu thank you for the info and also for the pull request.

    @Emill, is it possible to get your feedback on this? It seems like normalization by division is a pretty expensive way to fix this, especially since PostgreSQL is telling us exactly the number of digits (dscale) and we're not using it.

  21. added this to the milestone on Jul 25, 2017
  22. roji commented on Jul 28, 2017

    @roji
    Member

    Note: if #1651 is done then PR #1648 doesn't work any more, since we'd be supporting truly arbitrary-length decimals (and not just the 128-bit ones which .NET supports).

  23. modified the milestones: , Backlog on Mar 9, 2018
  24. removed this from the Backlog milestone on May 7, 2018
  25. added a commit that references this issue on May 7, 2018
    b96b288
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions