C# Dapper convert numbers to 2 decimals

I had this problem when inserting numbers into a SQL database using Dapper. All of my numbers did not round correctly when being inserted, even when using Math.Round() before doing the insert.

My class is something like this:

public class Product
{
    public int ID { get; set; }
    public float Price { get; set; }
    public float VolumePrice { get; set; }
    public float VolumeQuantity { get; set; }
}

And before I did the SQL insert, I made sure that the price was rounded to 2 digits:

// Pseudocode, imagine that you have a 
// source item and you update the SQL
// destination item 
var product = new Product();
product.ID = souce.ID;
product.Price = Math.Round(source.Price, 2);
product.VolumePrice = Math.Round(source.VolumePrice, 2);
product.VolumeQuantity = Math.Round(source.VolumeQuantity, 2);

But even with the Math.Round(), the SQL database inserts this:

Invalid rounded numbers when inserting floats
Invalid rounded numbers when inserting floats

It turns out, that inserting the data type float will cause the rounding issue. When I changed the data type to double, the issue went away:

public class Product
{
    public int ID { get; set; }
    public double Price { get; set; }
    public double VolumePrice { get; set; }
    public double VolumeQuantity { get; set; }
}

With the double data type, the rounding is accepted:

Using double as datatype, and dapper will recognize the rounding
Using double as datatype, and dapper will recognize the rounding

In other words: do not use float as datatype. Use double.

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c#, General .NET and tagged , , , , . Bookmark the permalink.

1 Response to C# Dapper convert numbers to 2 decimals

  1. Pingback: C# Dapper Async Bulk Inserts | Brian Pedersen's Sitecore and .NET Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.