-1

I am encountering a problem with preserving decimal precision while storing data in SQL Server from a C# application. Here's the scenario:

I have a C# application that retrieves exchange rate data from an API and then stores it in a SQL Server database. The exchange rates are fetched as decimal numbers with several decimal places of precision, for example, "0.037431."

However, when I store these values in SQL Server, they are rounded to two decimal places, resulting in values like "0.04" being saved in the database.

I've already tried changing the SQL Server column data type to decimal(18, 6) to preserve precision, but the problem persists. I suspect that there might be some configuration or formatting issues in my C# code or Entity Framework.

Here's a snippet of my C# code:

foreach (JProperty kvp in exchangeRateData["rates"])
{
    var rateString = kvp.Value.ToString();
    var rateDecimal = decimal.Parse(rateString, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture);

    var exchangeRate = new ExchangeRate
    {
        // Other properties
        Rate = rateDecimal
    };

    await _exchangeRateDal.Add(exchangeRate);
}

How can I ensure that the decimal precision is preserved when storing these values in SQL Server? Are there any additional steps or configurations I should consider? Any insights or guidance would be greatly appreciated.

I attempted to resolve this issue by first ensuring that the SQL Server column where I store the exchange rate values is defined as decimal(18, 6) to maintain precision. Additionally, I tried modifying the C# code to directly convert the JSON data to a decimal and then save it to the database. I expected that this configuration would allow me to store the exchange rates with their full precision, like "0.037431," in the SQL Server database.

However, the actual result is that the values are still being rounded to two decimal places when they are saved in the database, resulting in values like "0.040000." I suspect there might be something in my code or database configuration that I am missing, but I'm not sure what it is.

I'm looking for guidance on how to ensure that the full precision of the exchange rate values is preserved when saving them to SQL Server. Any suggestions or insights on what could be causing this issue would be greatly appreciated.

  • How is `ExchangeRate.Rate` mapped in EF? You should be able to specify the precision in the mapping. You need to also specify if you are using EF6 or a higher core version. – Igor Sep 02 '23 at 12:36
  • See the marked duplicate, you can find answers here for EF4 to EF6 and also answers for EF Core. – Igor Sep 02 '23 at 12:38

0 Answers0