CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: About decimals

  1. #1
    Join Date
    Apr 2011
    Posts
    3

    About decimals

    n00b question time ;-)

    I am wondering how to make a calculation with decimals. I'm trying to do this:

    result = numbers / percentage * 100;

    So numbers = 1863.8 , percentage = 20 , the result should be: 9319

    But instead I get an error because 1863.8 is not a valid int.

    I have no idea to solve this.

  2. #2
    Join Date
    Mar 2011
    Location
    London
    Posts
    54

    Re: About decimals

    Always need to be careful with type conversion.

    This code works here:
    Code:
    decimal numbers = 1863.8M;
    int percentage = 20;
    decimal result = 0.0M;
                
    result = numbers / percentage * 100;
    result = numbers / (decimal)percentage * 100M;
    Note in the first calculation I am combining a decimal, integer and integer and the result comes out ok. In the second one, I'm using a decimal, decimal (explicitly converted from integer) and a decimal (note the M at the end of 100).

    The second example is better because I'm being absolutely explicit about my conversions and not relying on the runtime to do the conversions for me implicitly which could lead to unusual results. When doing maths, I find it best to convert everything into the same type before doing my maths so that I know what I'm going to end up with.

  3. #3
    Join Date
    Apr 2011
    Posts
    3

    Re: About decimals

    Thank you for your usefull reply RedBully.

  4. #4
    Join Date
    Mar 2011
    Location
    London
    Posts
    54

    Smile Re: About decimals

    Glad I could be of help! Please mark this thread as resolved.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured