Skip to content

Numeric casts round instead of truncating, (byte) casts don't wrap, and BigInteger division isn't integer division #4095

Not planned

Description

@CaffeinatedCoder
Environment
PostgreSQL 18.6 (postgres:18), session TimeZone Etc/UTC
.NET 10 runtime 10.0.11, Npgsql.EntityFrameworkCore.PostgreSQL 10.0.3, EF Core 10.0.4
.NET 11 runtime 11.0.0-rc.2, Npgsql.EntityFrameworkCore.PostgreSQL 11.0.0-rc.2, EF Core 11.0.0-rc.2
Also Npgsql 10.0.3 on both lines, macOS arm64

Both lines print the same output. main at 150011d has the same code.

LINQ Row .NET PostgreSQL SQL
(int)r.Decimal 2.7m 2 3 r."Decimal"::int
(long)r.Double 2.7 2 3 r."Double"::bigint
(byte)r.Int == 249 −7 match no match r."Int"::smallint = 249
r.Big / r.Big2 == 3 7 / 2 match no match r."Big" / r."Big2" = 3
Repro
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System.Numerics;

await using var context = new TestContext();
await context.Database.EnsureDeletedAsync();
await context.Database.EnsureCreatedAsync();

context.Rows.Add(new Row { Decimal = 2.7m, Double = 2.7, Int = -7, Big = 7, Big2 = 2 });
await context.SaveChangesAsync();
var row = await context.Rows.AsNoTracking().SingleAsync();

// 1. C# casts truncate toward zero; ::int rounds
Console.WriteLine($"(int)2.7m: .NET {(int)row.Decimal}, database {await context.Rows.Select(r => (int)r.Decimal).SingleAsync()}");
Console.WriteLine($"(long)2.7: .NET {(long)row.Double}, database {await context.Rows.Select(r => (long)r.Double).SingleAsync()}");

// 2. An unchecked byte cast wraps; ::smallint keeps -7
Console.WriteLine($"(byte)-7 == 249: .NET {((byte)row.Int == 249 ? 1 : 0)}, database {await context.Rows.CountAsync(r => (byte)r.Int == 249)}");

// 3. BigInteger division is integer division
Console.WriteLine($"Big / Big2 == 3 (7 / 2): .NET {(row.Big / row.Big2 == 3 ? 1 : 0)}, database {await context.Rows.CountAsync(r => r.Big / r.Big2 == 3)}");

public class TestContext : DbContext
{
    public DbSet<Row> Rows => Set<Row>();

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseNpgsql(Environment.GetEnvironmentVariable("Test__Npgsql__DefaultConnection"), o => o.UseNodaTime())
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();
}

public class Row
{
    public int Id { get; set; }
    public decimal Decimal { get; set; }
    public double Double { get; set; }
    public int Int { get; set; }
    public BigInteger Big { get; set; }
    public BigInteger Big2 { get; set; }
}

Output, the same on both lines:

(int)2.7m: .NET 2, database 3
(long)2.7: .NET 2, database 3
(byte)-7 == 249: .NET 1, database 0
Big / Big2 == 3 (7 / 2): .NET 1, database 0
  • Casts. C# casts from decimal, double and float to an integer type truncate toward zero. PostgreSQL's casts round: half away from zero for numeric, half to even for float8. SQL Server's CAST truncates, so this is specific to this provider. The cast is rendered as ::int (NpgsqlQuerySqlGenerator.cs#L603-L626); trunc(x)::int would match .NET. Convert.ToInt32(decimal) goes the same way (NpgsqlConvertTranslator.cs#L36) and rounds half away from zero, where .NET rounds half to even.
  • byte maps to smallint, so an unchecked (byte) cast keeps −7 instead of wrapping to 249.
  • BigInteger maps to numeric (NpgsqlBigIntegerTypeMapping.cs#L30), so / is numeric division (3.5). div(a, b) matches BigInteger's truncating division.

Activity

  1. Zentauer commented on Nov 24, 2026

    @Zentauer
    Contributor

    Hey, I'd love to help. These three cases seem quite different to me, so it might make sense to handle them separately.

    The BigInteger division looks like a clear bug with a small fix. I would translate / between two BigInteger operands to PostgreSQL's div(a, b), which truncates towards zero just like BigInteger.Divide in .NET. The change would go into NpgsqlSqlTranslatingExpressionVisitor.VisitBinary, similar to the existing special case for LocalDate subtraction, and I would add a Divide test to BigIntegerTranslationsTest.

    The rounding in numeric casts seems more like a design decision, since switching to trunc() could change results for existing applications and affect index usage. The wrapping behavior of (byte) casts is probably hard to support, since PostgreSQL has no 1-byte integer type. I think both points should be clarified before any changes are made.

    Would a PR for the BigInteger division part be welcome?

  2. roji commented on Nov 24, 2026

    @roji
    Member

    @CaffeinatedCoder thank you for these bug reports, but can you please open individual issues for separate problems? Your issues have clumped together unrelated problems, making it difficult to track things properly.

    Am happy to receive individual bug reports (and PRs fixing them) - @Zentauer feel free to open a separate issue for that and a PR etc.

  3. CaffeinatedCoder commented on Nov 24, 2026

    @CaffeinatedCoder
    Author

    @roji Sorry for the inconvenience; I initially wanted to avoid opening a huge load of issues and tried to relate them as closely together by affected coarse subject. I will split them into separate issues.

  4. CaffeinatedCoder commented on Nov 24, 2026

    @CaffeinatedCoder
    Author

    @roji I've split the bundled issues as you asked: one issue per bug, each with its own repro, re-run on 10.0.4 and 11.0.0.

    From this issue:

    The others kept their first bug and point to the new issues:

    I left #4083, #4087, #4088, #4091, #4093, #4097 and #4099 as they are, since each has one root cause and one fix (#4116 fixes #4087 and both halves of #4088 in one change). If you'd rather have any of those split too, tell me and I'll do it.

  5. roji commented on Nov 25, 2026

    @roji
    Member

    Thanks @CaffeinatedCoder, much appreciated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    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