Repository navigation
Description
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
roji commentedon Mar 1, 2017
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.Emill commentedon Mar 1, 2017
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)roji commentedon Mar 1, 2017
I get 2.33 for both in psql, but 2.3300/2.33 via Npgsql.
jbourne2 commentedon Mar 1, 2017
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
roji commentedon Mar 1, 2017
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...
Emill commentedon Mar 1, 2017
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.
roji commentedon Mar 1, 2017
Feel like taking a look? You're the one who knows best that part
Emill commentedon Mar 1, 2017
Maybe in a week or so. Have to much other stuff to do...
roji commentedon Mar 1, 2017
OK, take your time :)
jbourne2 commentedon Mar 1, 2017
Thank you gentlemen; we appreciate it.
jbourne2 commentedon Mar 29, 2017
Hi @roji and @Emill , Quick follow up on this. Any development? Thank you very much.
roji commentedon Apr 2, 2017
I'm definitely not going to have any time to look at this anytime soon, @Emill take a look if you feel like it.
influento commentedon Apr 12, 2017
Hello. We stucked on this issue in our project too. Hope it will be solved, because we love npgsql
roji commentedon Apr 12, 2017
For anyone stuck on this, you can always work around it yourself (e.g. with
Math.Round).influento commentedon Apr 13, 2017
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.
StillLearnin commentedon May 16, 2017
@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.
StillLearnin commentedon May 16, 2017
GetValueandGetStringalso return 0.017745000roji commentedon May 17, 2017
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?DoraemonDesu commentedon Jul 18, 2017
Hello @roji and @jbourne2
Evidences are found regarding this bug:
NumericHandlerreads from buffer then constructs the decimal everytime methodRead()is calledNumericHandlergroups the digit and multiply them by a weight then and add them, for example:Decimal.GetBits()), the values are different. Because:Solutions
NumericHandlerbefore the value is returned (We will pull request on this issue).Results
src/Npgsql/TypeHandlers/NumericHandlers/NumericHandler.cstest/Npgsql.Tests/BugTests.csNumericHandlers, the result is normalized before returned.BugTests.cs, this will compare if value returned from PostgreSQL is the same as original after the values are decoded.Conclusion:
roji commentedon Jul 18, 2017
@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.
roji commentedon Jul 28, 2017
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).
Read dscale and round result to that precision