-1

I have two int numbers a, b always >= 0. I want to divide a by b and return the rounded up percentage to the nearest integer.

Example: 18/38 should return 47 and 13/38 should return 34.

How can I accomplish this?

I tried the following but it didn't work

c = Math.round(a/b) * 100;
Mureinik
  • 252,575
  • 45
  • 248
  • 283
BigMon
  • 41
  • 8
  • 1
    a/b is an integer division. You need to cast at least one of the operands to a double to have a double division. – JB Nizet May 07 '19 at 17:43

4 Answers4

3

Since a and b are integers, a/b will use integer division, and only return the "whole" part of the result. Instead, you should multiply a by 100.0 (note the .0, which makes it a double literal!) to use floating-point division, and then ceil the result, and truncate it to an int:

c = (int) Math.ceil(100.0 * a / b);
Mureinik
  • 252,575
  • 45
  • 248
  • 283
  • `c = (int) Math.round(100.0 * a / b);` will give 47 which is intended – Talha May 07 '19 at 17:50
  • Thank you for your answer! I'm getting 18/38=45 and 13/38=35 for some reason though? – BigMon May 07 '19 at 17:51
  • @BigMon the text of your question and the example you gave contradict each other. E.g., 13/38 is roughly 34.21% - if you want to round it up like the text says you'll get 35, which the code returns; If you want to get 34 that would be rounding down, and you should use `floor` instead of `ceil` - or, of course, you could just use `round` to get the nearest integer. – Mureinik May 07 '19 at 17:55
  • @Mureinik that's my bad, I changed ceil to round as you said and it seems to work as I want it. – BigMon May 07 '19 at 18:00
0
c = (int) Math.round(100.0 * a / b);

This should give desired result.

Shivam Mohan
  • 402
  • 2
  • 13
0

You need to do follow things to get the result

Double res= Double.valueof(a/b);
DecimalFormat decimalFormat = new DecimalFormat("#.00");
String num= decimalFormat.format(res);
Int finalResult = Integer.valueof(num)*100;

Thanks

0
public static void main(String[] args){
int a=18,b=38,c=0;
c = (int) Math.round(100.0 * a / b);    
System.out.println(c);
}

As @Mureinik said that a and b are integers,they will use integer division. you should multiply 100 by a like above. and keep using .round instead of .ceil inorder to get 47 as output which is intended .ceil will give you 48 as output.

Talha
  • 546
  • 1
  • 6
  • 21