Skip to content

Overflow exception with seemingly fine numeric value #4299

Closed as not planned
Closed as not planned

Description

@dmdymov

Please clarify what I am doing wrong here.

Steps to reproduce

// connection init
// ...

using (var cmd = new NpgsqlCommand("select 794866.99999999999999999999999", conn))
{
    using (var reader = await cmd.ExecuteReaderAsync())
    {
        while (await reader.ReadAsync())
            Console.WriteLine(reader.GetDecimal(0));
    }
}

The issue

I'm getting an overflow exception at GetDecimal.

 System.OverflowException: Numeric value does not fit in a System.Decimal
   at void Npgsql.Internal.TypeHandlers.NumericHandlers.DecimalRaw.Multiply(ref DecimalRaw value, uint multiplier) in /_/src/Npgsql/Internal/TypeHandlers/NumericHandlers/DecimalRaw.cs:line 119
   at async ValueTask<decimal> Npgsql.Internal.TypeHandlers.NumericHandlers.NumericHandler.Read(NpgsqlReadBuffer buf, int len, bool async, FieldDescription fieldDescription) in /_/src/Npgsql/Internal/TypeHandlers/NumericHandlers/NumericHandler.cs:line 99
   at T Npgsql.NpgsqlDataReader.GetFieldValue<T>(int ordinal) in /_/src/Npgsql/NpgsqlDataReader.cs:line 1640

I've read #3627.

The value 99999999999.0000000000000000000 has 30 digits, but the .NET decimal type only supports up to 29 digits, so Npgsql cannot read that value correctly

My value has 29 digits and still causes an exception.

Further technical details

Npgsql version: 6.0.3
PostgreSQL version: PostgreSQL 10.5 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-28), 64-bit
Server operating system: Red Hat Enterprise Linux Server release 7.5 (Maipo)
Client operating system:: Microsoft Windows Server 2012 R2 Standard
TargetFramework: netcoreapp2.0

Thanks.

Activity

  1. changed the title [-]Overflow exception with seemingly good numeric value[/-] [+]Overflow exception with seemingly fine numeric value[/+] on Jan 28, 2022
  2. roji commented on Jan 28, 2022

    @roji
    Member

    @dmdymov I don't have a precise answer - it's possible that the decimal is rounded or slightly tweaked as part of binary encoding/decoding.

  3. vonzshik commented on Jan 28, 2022

    @vonzshik
    Contributor

    @roji seems like a bug on our side. To repro:

    var dr = new DecimalRaw(794.86699999999999999999999m);
    Assert.DoesNotThrow(() => DecimalRaw.Multiply(ref dr, 1000));
  4. roji commented on Jan 28, 2022

    @roji
    Member

    @vonzshik ok, thanks for looking... I admit I don't know much about the decimal decoding/encoding. Do you want to investigate this?

  5. added this to the Backlog milestone on Jan 28, 2022
  6. vonzshik commented on Jan 28, 2022

    @vonzshik
    Contributor

    There is also a problem with division...

    var dr = new DecimalRaw(794866.99999999999999999999m);
    var expected = 794.86699999999999999999999m;
    DecimalRaw.Divide(ref dr, 1000);
    Assert.AreEqual(dr.Value, expected);
    Expected: 794.86699999999999999999m
    But was:  794.86699999999999999999999m
    

    @roji I can try, it's definitely not a trivial thing)

  7. Emill commented on Feb 7, 2022

    @Emill
    Contributor

    The answer is very simple: the numeric value does not fit in a System.Decimal.

    A System.Decimal is represented using a 96-bit integer, one "scale" field (0-28) containing number of digits to the right of the decimal separator, and one sign bit indicating if the number is negative or non-negative.

    Your number with the decimal separator removed, is 79486699999999999999999999999, which uses 97 bits and is hence out of range. If you print this number using Console.WriteLine(794866.99999999999999999999999M);, the compiler will first round it to 794867.0000000000000000000000, which does fit in a System.Decimal.

  8. vonzshik commented on Feb 8, 2022

    @vonzshik
    Contributor

    @Emill even so, there are a few cases I'm not so sure about:

    [Test]
    public void Divide()
    {
    	var dr = new DecimalRaw(794866.1m);
    	var expected = 794.8661m;
    	DecimalRaw.Divide(ref dr, 1000);
    	Assert.AreEqual(expected, dr.Value);
    }

    This one fails with:

    Expected: 794.8661m
    But was:  794.8m
    

    And there is also this one:

    [Test]
    public void Multiply()
    {
    	var dr = new DecimalRaw(794.86611111111111111111111m);
    	var expected = 794866.11111111111111111111m;
    	DecimalRaw.Multiply(ref dr, 1000);
    	Assert.AreEqual(expected, dr.Value);
    }

    That one fails with:

    System.OverflowException : Numeric value does not fit in a System.Decimal
    

    But I've also made a console app, which does prove that decimal can handle this value:

    var d1 = 794.86611111111111111111111m;
    var d2 = 794866.11111111111111111111m;
    var d3 = d1 * 1000;
    
    Console.WriteLine($"First decimal: {d1}");
    Console.WriteLine($"Second decimal: {d2}");
    Console.WriteLine($"Third decimal: {d3}");
    Console.WriteLine($"Second decimal is equal to third decimal: {d2 == d3}");
    Console.ReadKey();

    Output:

    First decimal: 794,86611111111111111111111
    Second decimal: 794866,11111111111111111111
    Third decimal: 794866,1111111111111111111100
    Second decimal is equal to third decimal: True
    
  9. Emill commented on Feb 8, 2022

    @Emill
    Contributor

    Why do we have a DecimalRaw class anyway? Can't we just use decimal directly, by first creating a 96-bit integer, then multiply by a scale factor such as 0.0001M or -0.0001M to insert the decimal separator and sign?

  10. roji commented on Feb 8, 2022

    @roji
    Member

    Why do we have a DecimalRaw class anyway?

    I don't really know enough to answer this... @YohDeadfall did this in 7f49d3b, maybe he can shed some light on that...

    In any case, if we think we can rewrite this without DecimalRaw in a way that's correct and just as fast, I definitely wouldn't be against it :)

  11. roji commented on Feb 8, 2022

    @roji
    Member

    by first creating a 96-bit integer

    BTW what would you use for this?

  12. Emill commented on Feb 8, 2022

    @Emill
    Contributor

    decimal ;)

  13. roji commented on Feb 8, 2022

    @roji
    Member

    Ah I see, I misread...

  14. YohDeadfall commented on Feb 8, 2022

    @YohDeadfall
    Contributor

    DecimalRaw is an internal type present in .NET itself for mutating decimals which are immutable. In case of Npgsql it's used to speed up reading and writing numbers by using integer operations only.

  15. YohDeadfall commented on Feb 8, 2022

    @YohDeadfall
    Contributor

    @roji, assign it to me. Will take a look when get some time.

  16. roji commented on Feb 8, 2022

    @roji
    Member

    @YohDeadfall thanks for commenting... See @Emill's suggestion to just perform the operations directly on decimal - I'm guessing the idea with DecimalRaw is to do the operations in-place so as to gain performance?

  17. YohDeadfall commented on Feb 8, 2022

    @YohDeadfall
    Contributor

    Not only because of that, but also to avoid creation of a secondary decimal from an integer. Internally decimal has DecCalc which serves the same purpose, and which is the same type we have, I just copy pasted some pieces of code we needed for quick math on integers. In addition to that, doing parsing this way keeps the scale as is and allows the driver to avoid rounding.

  18. vonzshik commented on Feb 8, 2022

    @vonzshik
    Contributor

    Just one more thing. I played a bit with decimals without explicitly calling DecimalRaw, and so far I hasn't been able to break it.
    There might be a potential issue whenever PG returns a negative scale, but I'm not sure that's actually possible...

  19. Emill commented on Feb 8, 2022

    @Emill
    Contributor

    If I remember correctly, "exponential" is a feature of CockroachDB or something not present in original postgresql.

    I don't see why multiplying by 0.00001M would introduce any rounding.

  20. YohDeadfall commented on Feb 21, 2022

    @YohDeadfall
    Contributor

    Good news, everyone! This is not a bug and by design, that's fine.

    The author didn't took into account how decimal works under the hood. It's a 96 bit integer with a floating point, so to check if a number fits you have to compare values without taking the scale. Therefore, 794866.99999999999999999999999 has without dot looks like 79486699999999999999999999999, and this value should be stored in 96 bits, but the maximum is 79228162514264337593543950335. As you can see, the problematic value simply doesn't fit into decimal.

  21. added theissue type on Jun 18, 2025
  22. removed this from the Backlog milestone on Nov 5, 2025
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

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions