28

I want to know how to get remainder and quotient in single value in Java.

Example:

3/2 I should get value as 1.5.

If I use the / operator I get only the quotient. If I user the % operator I get only the remainder. How do I get both at a time in the same variable?

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102

10 Answers10

58
quotient = 3 / 2;
remainder = 3 % 2;

// now you have them both
recursive
  • 83,943
  • 34
  • 151
  • 241
  • 2
    @endless: True, you'd have to convert to integer first. And you'd also have to specify what you mean by remainder of two floats, since it's usually defined in terms of integer arithmetic. – recursive Apr 25 '13 at 19:13
  • Just if somebody goes over this question and wonders how you would get not the quotient, but the largest natural number <= the quotient or the mod you can use the function in the math package: `Math.floorDiv(x,y)` and `Math.floorMod(x,y)` – Frank Essenberger Aug 15 '16 at 07:28
  • perfect and simple. Thanks – Septronic Jul 06 '17 at 22:47
22

In your example, Java is performing integer arithmetic, rounding off the result of the division.

Based on your question, you would like to perform floating-point arithmetic. To do so, at least one of your terms must be specified as (or converted to) floating-point:

Specifying floating point:

3.0/2
3.0/2.0
3/2.0

Converting to floating point:

int a = 2;
int b = 3;
float q = ((float)a)/b;

or

double q = ((double)a)/b;

(See Java Traps: double and Java Floating-Point Number Intricacies for discussions on float and double)

vladr
  • 65,483
  • 18
  • 129
  • 130
8

Check this out: http://download.oracle.com/javase/1,5.0/docs/api/java/math/BigDecimal.html#divideAndRemainder%28java.math.BigDecimal%29

You just need to wrap your int or long variable in a BigDecimal object, then invoke the divideAndRemainder method on it. The returned array will contain the quotient and the remainder (in that order).

  • This is a great answer in that it does answer what the OP is looking for. One does need to ask though does giving up using a 32 bit primitive for a BigDecimal counteract any savings that one would theoretically get (if the compiler did not perform the optimizations for you)? – demongolem Sep 03 '15 at 19:20
7

Don't worry about it. In your code, just do the separate / and % operations as you mention, even though it might seem like it's inefficient. Let the JIT compiler worry about combining these operations to get both quotient and remainder in a single machine instruction (as far as I recall, it generally does).

Neil Coffey
  • 21,615
  • 7
  • 62
  • 83
2

I mean it's quite simple. Set it as a double. So lets say

double answer = 3.0/2.0;
System.out.print(answer);
Adan Vivero
  • 422
  • 12
  • 36
1

If you initialize both the parameters as float, you will sure get actual divided value. For example:

float RoomWidth, TileWidth, NumTiles;
RoomWidth = 142;
TileWidth = 8;
NumTiles = RoomWidth/TileWidth;

Ans:17.75.

Alok
  • 2,629
  • 4
  • 28
  • 40
1
int a = 3;
int b = 2;
float c = ((float)a)/b
Matthew
  • 11
  • 1
  • 1
    You could improve this answer by briefly describing what your code does. For example why is it necessary to convert a to a float before the division. – Greg the Incredulous Mar 15 '17 at 04:24
1

You can do like,

int a = 3;
int b = 2;
int quotient = a / b;
int remainder = a % b;

To get quotient in real numbers

System.out.println((double) a / b);

To get quotient in integer numbers

System.out.println("Quotient: " + quotient);
System.out.println("Remainder: " + remainder);

To get quotient in real number such that one number after decimal

System.out.println(a / b + "." + a % b * 10 / b);

Note: In the last method it will not round the number up after the decimal.

0

@recursive's solusion (The accepted answer) is 100% right. I am just adding a sample code for your reference.

My case is to display price with two decimal digits.This is part of back-end response: "price": 2300, "currencySymbol": "CD", ....

This is my helper class:

public class CurrencyUtils
{
    private static final String[] suffix = { "", "K", "M" };

    public static String getCompactStringForDisplay(final int amount)
    {
        int suffixIndex;
        if (amount >= 1_000_000) {
            suffixIndex = 2;
        } else if (amount >= 1_000) {
            suffixIndex = 1;
        } else {
            suffixIndex = 0;
        }

        int quotient;
        int remainder;
        if (amount >= 1_000_000) {
            quotient = amount / 1_000_000;
            remainder = amount % 1_000_000;
        } else if (amount >= 1_000) {
            quotient = amount / 1_000;
            remainder = amount % 1_000;
        } else {
            return String.valueOf(amount);
        }

        if (remainder == 0) {
            return String.valueOf(quotient) + suffix[suffixIndex];
        }

        // Keep two most significant digits
        if (remainder >= 10_000) {
            remainder /= 10_000;
        } else if (remainder >= 1_000) {
            remainder /= 1_000;
        } else if (remainder >= 100) {
            remainder /= 10;
        }

        return String.valueOf(quotient) + '.' + String.valueOf(remainder) + suffix[suffixIndex];
    }
}

This is my test class (based on Junit 4):

public class CurrencyUtilsTest {

    @Test
    public void getCompactStringForDisplay() throws Exception {
        int[] numbers = {0, 5, 999, 1_000, 5_821, 10_500, 101_800, 2_000_000, 7_800_000, 92_150_000, 123_200_000, 9_999_999};
        String[] expected = {"0", "5", "999", "1K", "5.82K", "10.50K", "101.80K", "2M", "7.80M", "92.15M", "123.20M", "9.99M"};

        for (int i = 0; i < numbers.length; i++) {
            int n = numbers[i];
            String formatted = CurrencyUtils.getCompactStringForDisplay(n);
            System.out.println(n + " => " + formatted);

            assertEquals(expected[i], formatted);
        }
    }

}
Hesam
  • 52,260
  • 74
  • 224
  • 365
0

Please Convert your input in double and divide.