We help IT Professionals succeed at work.

Modulus operator in java

pkvrajan
pkvrajan asked
on
Medium Priority
8,055 Views
Last Modified: 2011-05-11
I wrote a program for checking modulus.. Here it is.
public class TestModulus
{
     public static void main(String[] args)
     {
          System.out.println("Test modulus -------->"+Double.valueOf(args[0]).doubleValue() % Double.valueOf(args[1]).doubleValue());
          System.out.println("Test modulus -------->"+Double.valueOf(args[0]).doubleValue() / Double.valueOf(args[1]).doubleValue());
     }
}


Output
---------------
java  TestModulus 116 5.8
Test modulus -------->3.552713678800501E-15
Test modulus -------->20.0


Please tell me why modulus does not give 0 in this case?..
Thanks in advance.
Comment
Watch Question

Peter KwanAnalyst Programmer

Commented:
Here is exactly your problem:
http://forum.java.sun.com/thread.jsp?forum=256&thread=47243

You may try the suggested solution to solve your problem.

Commented:
The double numbers when they're stored in the memory, they have some error, that means 116 may be stored as 115.99999999999999999. So the modulus operation returns 3.552...E-15 is something very near zero.
daitt

Commented:
pkvrajan: finalize this question please

Author

Commented:
Dear daitt
I an convinced with ur explanation.  But I am lokking for a way to solve the problem.  will BigDecimal help in this case?.

Regards
Pkvrajan

Commented:
Sorry I thought you only want to know why.
Yes, BigDecimal is based on 10, so it would solve your problem.
Sample code:

import java.math.*;

public class Test
{
public static void main(String[] args)
{
     BigDecimal dec = new BigDecimal(new BigInteger("116"),0);
     BigDecimal dec2 = new BigDecimal(new BigInteger("58"),1);
     BigDecimal result = dec.divide(dec2,BigDecimal.ROUND_UNNECESSARY);
     System.out.println("Value:"+result.intValue()+" * 10^"+result.scale());
}
}
Commented:
some comments: it works for this situation, but for all the cases, you must catch ArithmeticException.
Mod = 0 when:
1. There's no ArithmeticException
2. Scale must be zero.
So instead of:
BigDecimal result = dec.divide(dec2,BigDecimal.ROUND_UNNECESSARY);
You can specify scale = 0:
BigDecimal result = dec.divide(dec2,0,BigDecimal.ROUND_UNNECESSARY);

in this case, ArithmeticException occurs if mod!=0. If mod=0, the divide function will return the result.

Author

Commented:
Dear Daitt
I have accepted ur idea as answer.  Thanks a lot.
Regards
Karthik