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:
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:
In other words: do not use float as datatype. Use double.
MORE TO READ: