How do I divide an int by 100?
eg:
int x = 32894;
int y = 32894 / 100;
Why does this result in y being 328 and not 328.94?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
When one integer is divided by another, the arithmetic is performed as integer arithmetic.
If you want it to be performed as float, double or decimal arithmetic, you need to cast one of the values appropriately. For example:
Note that I’ve changed the type of
yas well – it doesn’t make sense to perform decimal arithmetic but then store the result in anint. Theintcan’t possibly store 328.94.You only need to force one of the values to the right type, as then the other will be promoted to the same type – there’s no operator defined for dividing a decimal by an integer, for example. If you’re performing arithmetic using several values, you might want to force all of them to the desired type just for clarity – it would be unfortunate for one operation to be performed using integer arithmetic, and another using double arithmetic, when you’d expected both to be in double.
If you’re using literals, you can just use a suffix to indicate the type instead:
As for whether you should be using
decimal,doubleorfloat, that depends on what you’re trying to do. Read my articles on decimal floating point and binary floating point. Usuallydoubleis appropriate if you’re dealing with “natural” quantities such as height and weight, where any value will really be an approximation;decimalis appropriate with artificial quantities such as money, which are typically represented exactly as decimal values to start with.