-2

Im getting totally wrong when calling CorrectDecimals with the following parameters:

203,30 - 203,00. Gives me: 0.30000000000001137 (the variable double d). With my mathematical skills it should just be 0.3

string a = CorrectDecimals("203,30", "203,00", "12");

public static string CorrectDecimals(string unitPrice, string netAmount, string length)
{
            double unitP = (Double.Parse(unitPrice));
            double netAmoun = (Double.Parse(netAmount));
            double d = unitP - netAmoun;
Sindresvends
  • 180
  • 1
  • 1
  • 10

2 Answers2

2

When working with financial data (prices, amount etc.) use Decimal instead of double/float:

   string a = CorrectDecimals("203,30", "203,00", "12");

   public static string CorrectDecimals(string unitPrice, string netAmount, string length)
   {
       decimal unitP = decimal.Parse(unitPrice);
       decimal netAmoun = decimal.Parse(netAmount);
       decimal d = unitP - netAmoun;

In case you have to implement the routine in double, use formatting:

       double d = unitP - netAmoun;
       ...
       // 2 digits after decimal point
       string result = d.ToString("F2"); 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0
    public static string CorrectDecimals(string unitPrice, string netAmount, string length)
    {
        decimal unitP = (decimal.Parse(unitPrice));
        decimal netAmoun = (decimal.Parse(netAmount));
        decimal d = unitP - netAmoun;
        string result = d.ToString();

        return result;
    }

Use decimal instead of double.

RobertPeric
  • 51
  • 1
  • 6