What do I do if I want to divide only tens? for example I have 16 when I divide it to 10 it will only answer 1 if I do 23 it will give me 2, like what I want to do is like diving 20(example) and 10 and it is ignoring the 6 in 26.
Asked
Active
Viewed 652 times
3 Answers
0
Integer values ignore decimal places in division:
int num = 236;
int div = num / 10;
int remainder = num % 10;
System.out.println("div = " + div);
System.out.println("remainder = " + remainder);
You can however use float
or double
instead though to get those decimal placed and then optionally round the result back to an integer.
double withDecimal = (double) num / 10.0;
int rounded = (int) Math.round(withDecimal);
System.out.println("withDecimal = " + withDecimal);
System.out.println("rounded = " + rounded);

Locke
- 7,626
- 2
- 21
- 41
-
in this case `round` method will not work since it return, for example, 80 for 79.60 which the question wants to get 79 – Morteza Oct 10 '20 at 04:33
0
Integer
division in Java truncates decimals (hence the name). In order to maintain the decimals you have to make at least one of the variables a double
or float
like so:
double x = 16 / 10.0; //1.6
double y = 23 / 10.0; //2.3

Kel Varnsen
- 314
- 2
- 8
0
Step 1: get the reminder by using number % 10;
Step 2: substract the reminder from the original number and store the result in a variable
Step 3: now divide the new number by 10.
public static void main(String []args){
int number = 33;
int reminder = number % 10;
number = number - reminder;
System.out.println(number / 10);
}

Saiful Islam
- 1,151
- 13
- 22