Format Numbers to 2 Decimals in C# with Dapper

By FoxLearn 1/18/2025 2:33:47 AM   59
If you encounter an issue when inserting numeric data into a SQL database using Dapper.

Despite using Math.Round() to round values to two decimal places before insertion, the numbers were not rounding correctly when saved to the database.

public class Order
{
    public int ID { get; set; }
    public float TotalAmount { get; set; }
    public float DiscountAmount { get; set; }
    public float ShippingCost { get; set; }
}

Before executing the SQL insert, I made sure to round the TotalAmount, DiscountAmount, and ShippingCost to two decimal places:

// Pseudocode: imagine we have an order object, 
// and we want to insert it into the database 
var order = new Order();
order.ID = source.ID;
order.TotalAmount = Math.Round(source.TotalAmount, 2);
order.DiscountAmount = Math.Round(source.DiscountAmount, 2);
order.ShippingCost = Math.Round(source.ShippingCost, 2);

However, even with the rounding logic in place, the inserted values still had issues with rounding:

Inaccurate numbers inserted into SQL database

It turned out the problem was caused by using float as the data type. When I switched to using double, the issue disappeared:

public class Order
{
    public int ID { get; set; }
    public double TotalAmount { get; set; }
    public double DiscountAmount { get; set; }
    public double ShippingCost { get; set; }
}

By using double as the data type, Dapper properly handled the rounding: Rounding works correctly with double as the data type.

Don't use float for decimal or monetary values in your models. Instead, use double to ensure proper rounding and accuracy when working with Dapper and SQL.