|
-
April 14th, 2011, 10:37 AM
#1
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.
-
April 14th, 2011, 12:23 PM
#2
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.
-
April 15th, 2011, 09:29 AM
#3
Re: About decimals
Thank you for your usefull reply RedBully.
-
April 15th, 2011, 09:49 AM
#4
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|