Link to home
Start Free TrialLog in
Avatar of fks
fksFlag for India

asked on

Mathematical Operation on Int type

hi, see this.

I have this,

**********

out.println(po_total);
out.println(balance_total);
out.println(in_total);

int a =0;
a = balance_total/po_total;
out.println(a);

*********

All the varible here is declare as int. I can see the output of the po_total, balance_total, and also in_total.

but when i want to calculate % of the certain value, oppss, sorry. Actually the main purpose for me to code this is to find out the percentage of the value. The formula is balance_total/po_total*100. And i want to do it step by step.

So, the output of a is "0". ???

Yes, maybe it's because of int right?, then I have to change the a to double using this code,

double a =0.00;
a = balance_total/po_total;
out.println(a)

ha.. this time it's give me "0.0"

what's wrong??
 
Avatar of thanassis
thanassis

a is double. but balance_total & po_total are integers!

For java this is a problem!

So you have to declare both balance_total & po_total as doubles!
Hi,

Your problem is that balance_total and po_total both are ints. That makes that the result of balance_total/po_total is an int. You point to this int with a double reference named 'a' but that doesn't change the value you're referring to.
So you have to make at least one of both numbers a double or at least cast it to a double like:

double a =0.00;
a = (double )balance_total/po_total;

or
double a =0.00;
a = balance_total/(double )po_total;

Succes!



if you need percentage, just do:

double a = balance_total * 100.0 / po_total;

100.0 make it a double constant (because of .0), then java will promote int to double and calculate the result.
Avatar of fks

ASKER

ken, if my

balance_total=16
po_total=44

and a = 16*100.0/44
      = 36.36363636363636
??Ha...

I thouhgt i have declare in 100.0 then what happend.

>> I thouhgt i have declare in 100.0 then what happend.
i don't understand you. isn't that you want to get percentage, 16 over 44 is 36.36363636363636%, which is correct.
Avatar of fks

ASKER

ken, if my

balance_total=16
po_total=44

and a = 16*100.0/44
      = 36.36363636363636
??Ha...

I thouhgt i have declare in 100.0 then what happend.

Avatar of fks

ASKER

ken, I prefer 36.4% instead of 36.36363636

and i have declare on decimal point only riught?

Do I need to use the DecimalFormat to format it?
Yes you have to use Desimal format, like this:

import java.text.*;

DecimalFormat df = new DecimalFormat("#,##0.0;(#,##0.0)");
double a = balance_total*100.0/po_total;
out.println("a="+df.format(a));
ASKER CERTIFIED SOLUTION
Avatar of kennethxu
kennethxu

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial