Philly

hi chaps,

can anyone tell me how to work with decimal numbers

basicly i have the following,

int value = tb.Value;

decimal percent = (decimal)(value / 18 * 100);

using this keeps return 0 or if the value is 18 then it will return 100, but, say the value is 2 it will return 0 when it should be 11.11

thanks.

Philly



Re: Visual C# General working with decimals

Alberto Poblacion

Since the two values that you are dividing are integers, the compiler generates an integer division, and therefore you never get any decimals. You can fix it by converting either parameter to decimal before dividing. The following changes everything to decimal before performing the operations:

decimal percent = (decimal)value / 18m * 100m;





Re: Visual C# General working with decimals

Philly

thanks alberto, worked like a charm, was banging my head off the wall with this problem.

thanks again

Philly





Re: Visual C# General working with decimals

Matthew Watson

Also: Are you sure you should be using decimal, rather than double
decimal types are generally NOT needed, and doubles are far better to use (normally).




Re: Visual C# General working with decimals

Alberto Poblacion

That depends on what you are doing. If you are storing monetary values and you need them to be accurate to two decimal places (for instance), then it is a bad idea to store them as doubles. The reason is that the doubles store the number converted to base 2, and there are some numbers that have a finite number of decimal places in base 10 but have infinite decimals in base 2. Since the double does not store infinite digits, it will lose a little bit of your original number. For instance, a number such as "123.45" in base 10 might be converted into a base 2 representation which, after being truncated and then converted back to base 10, might be something similar to "123.44999999999998". This means that you have to be very careful about rounding it back to two decimal places before operating with it or displaying it. This problem does not happen with Decimals, which (contrary to Doubles) store an accurate representation of the base 10 numbers.





Re: Visual C# General working with decimals

Matthew Watson

Indeed, and normally you are NOT dealing with currencies.