0

in Excel if I have the following Values in row 1 cells A,B,C respectively

3.332125, 100%, 0% and for Cell $D$1 I have the formula : =($A$1*$B$1*($C$1+100%)+0.16)

This gives a value of 3.492125 which is what I want. I need to convert this to a C# formula and the problem I have is interpreting the 100%.

Can anyone offer the equivalent in C#

bilpor
  • 3,467
  • 6
  • 32
  • 77
  • This question denotes that your ideas regarding numbers in both Excel & C# (.NET and/or most of programming languages) are not too clear. One thing is the number (used to perform calculations) and a different story is the way in which it is being displayed. For example, if you write 100% in an Excel cell, you might see 100% or 1 or 1€, etc.. (depending upon the format of the given cell). C# behaves equivalently, by bearing in mind that it does not recognise "100%" as intuitively as Excel. Thus and by remembering that 100% equals 1 (50%, 0.5 and so on), you shouldn't have any problem. – varocarbas Sep 03 '15 at 08:57

2 Answers2

0

The Percentages must first be converted from strings. From This simmilar stack overflow question:

public decimal GetDecimalFromString(string valu)
{
    return decimal.Parse( valu.TrimEnd( new char[] { '%', ' ' } ) ) / 100M;
}

Essentially, num will be the Decimal value of, the string value, with the chars "%" and/or " " (space) Taken of the end, divided by 100. This will give your percentages as a decimal.

Then we can create a method to impliment your formula:

public decimal YourFormula(decimal A, decimal B, decimal C)
{
    return(A*B*(C+1)+0.16);
}

The 1 here is equal to 100%, as in excel

Community
  • 1
  • 1
Aidan Connelly
  • 164
  • 3
  • 13
  • Not sure this will work if I do the following in an Excel Formula `(0+100%)` will give `1` if i do `(1+100%)` will give` 2`. If I do this in C# by simply removing the % then `(1 + 100m) / 100m` will give `1.01` – bilpor Sep 03 '15 at 08:27
0
double a = 3.332125;
double b = 100/100;
double c = 0 / 100;
Console.WriteLine((a * b * (c + 100 / 100) + 0.16).ToString());

Result:

3.492125

Replace % with /100

Adrian Stanculescu
  • 1,040
  • 2
  • 13
  • 21