Home > Software engineering >  Decimal Trimmed after 2 digits added Zeros while store to SQL Server
Decimal Trimmed after 2 digits added Zeros while store to SQL Server

Time:01-05

I trying to store the Latitude and Longitude to my database.

I have these columns in my table:

[Latitude]  NUMERIC(12, 8) NULL,
[Longitude] NUMERIC(12, 8) NULL,

In the C# model class, my properties are:

[Column(TypeName = "numeric")]
[Range(-9999.99999999, 9999.99999999)]
public decimal? Latitude { get; set; }

[Column(TypeName = "numeric")]
[Range(-9999.99999999, 9999.99999999)]
public decimal? Longitude { get; set; }

I want to store these Latitude and Longitude values into my database table.

What am I doing wrong here? Please help

decimal lats = decimal.Parse("56.12345678");
decimal longs = decimal.Parse("10.18732210");

context.test.Add(new test
        {
            Latitude = lats,
            Longitude = longs
        });
context.SaveChanges();

It stores the values in the database table like this:

Latitude: 56.12000000  
Longitude : 10.18000000

I want the same value to be stored in the database:

"56.12345678"     
"10.18732210"

CodePudding user response:

You probably need to specify it also in your OnModelCreating like this:

modelBuilder.Entity<Test>().Property(a => a.Latitude).HasPrecision(18, 9);
modelBuilder.Entity<Test>().Property(a => a.Longitude).HasPrecision(18, 9);

Just in case you need more advanced features and you are using EF Core take a look at: https://docs.microsoft.com/en-us/ef/core/modeling/spatial

  •  Tags:  
  • Related