Question

I am trying to figure out why my decimal values are not being stored correctly. This is an example equation:

//Comes up as 0.0
double foo = 120 / 175;
// Want to convert to look like a percent but comes up as 0.0 also
double bar = foo * 100;

I know 120/175 is 0.6857.... any idea?

Was it helpful?

Solution

You're performing arithmetic on two integers, so the result is an integer. You lose the fractional part of the result before it's stored in foo.

You should convert one of the values to a double first:

double foo = 120d / 175;

You can do this with decimals too, if that's what you're actually trying to use:

decimal foo = 120m / 175;

Once you've properly captured the decimal value from the first equation, this part should work fine:

decimal bar = foo * 100;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top