We help IT Professionals succeed at work.

# Modulus operator in java

on
Medium Priority
8,055 Views
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?..
Comment
Watch Question

## View Solution Only

Analyst Programmer

Commented:

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:

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.