(Newbie) Needs help with math equation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • bencoding
    New Member
    • Mar 2008
    • 21

    (Newbie) Needs help with math equation

    Hello, I've been learning C# for a few months now and still learning, I come from a PHP background where declaring the variable types is not involved.

    I would like to do this simple math problem in C#, is there anyone who can help me?

    Number A: Is a monetary value with dollars and cents (eg 199.95)
    Number B: Is a numerical percentage value (eg 90%) without the percent sign


    My code here returns $17995.50 when the answer I am looking for is $179.95

    Code:
            
    decimal DollarAmt = 199.95;
    int PercentAmt = 90;
    
    decimal result = DollarAmt * PercentAmt ;
    
    //returns bad result of 17995.50 - help!
    Response.Write(result);
  • developing
    New Member
    • Mar 2007
    • 110

    #2
    hey

    firstly, you should post this in C# section and not in C/C++ section

    now, when you look at 90%, you realize that it is 90 of 100 or 90/100.

    c# doesnt know that, so you need to divide 'PercentAmt' by 100 by

    Code:
    PercentAmt /= 100;
    also, since you are doing this for the web, i recommend using 'float' or 'double' instead of 'decimal' as they take less memory.

    float - 32 bit
    double - 64 bit
    decimal - 128 bit

    Comment

    • bencoding
      New Member
      • Mar 2008
      • 21

      #3
      ok, thanks, I didn't see the C# section before,.... that was helpful and got me one step closer, so when I do this I get a long string past the decimal, is there a round() function that will round it up to the nearest cent? (see my code results)
      Code:
              float per = 90;
              float conv_per = p / 100;
      
              double dol = 199.95;
      
              double a = conv_p * dol;
      
              // Returns 179.95499523282 
              Response.Write(a);

      Comment

      • bencoding
        New Member
        • Mar 2008
        • 21

        #4
        ah I found this,

        Code:
        Math.Round(result,2);

        works! thanks for the help.

        Comment

        • developing
          New Member
          • Mar 2007
          • 110

          #5
          Code:
          Math.Round(a, 2);
          that should be it.

          Comment

          Working...