Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I cannot the get percentage by using Int

Tags:

Please forgive my programming knowledge. I know this is a simple thing, but I do not understand why result is always 0. Why decimal will be fine?

int a = 100;
int b = 200;
decimal c = (a / b) * 100;

Many thanks.

like image 415
Daoming Yang Avatar asked Apr 08 '10 17:04

Daoming Yang


People also ask

Can a percentage be an integer?

Integers are whole numbers and their negative opposites. Therefore, these numbers can never be integers: fractions. decimals. percents.

How do I turn a number into a percentage?

To convert a decimal to a percentage, multiply by 100 (just move the decimal point 2 places to the right). For example, 0.065 = 6.5% and 3.75 = 375%. To find a percentage of a number, say 30% of 40, just multiply. For example, (30/100)(40) = 0.3 x 40 = 12.

How do you convert int to percentage in Java?

so basically you can just do it like this: dogs = (population * percentage)/100; cats = (population - dogs); as dogs and population must to be Integers. Show activity on this post.


2 Answers

Integer division always truncates the remainder. This is done at the time that the number is divided, not when it's assigned to the variable (as I'm guessing you assumed).

decimal c = ((decimal)a / b) * 100;
like image 58
Adam Robinson Avatar answered Sep 25 '22 01:09

Adam Robinson


The value a/b will return 0 always since they are integers. So when the values within the Brackets are evaluated you are technically doing this

decimal c = (0) * 100

Better do,

decimal c = ((decimal)a/(decimal)b) * 100
like image 34
bragboy Avatar answered Sep 24 '22 01:09

bragboy