Why does this code print 2.4099999999999997, instead of just 2.41
public class Main
{
public static void main(String args[])
{
double d = 5.55%3.14;
System.out.println(d);
}
}
Why does this code print 2.4099999999999997, instead of just 2.41
public class Main
{
public static void main(String args[])
{
double d = 5.55%3.14;
System.out.println(d);
}
}
The problem is not the modulo operator, but rather the nature of floating point numbers. A double cannot hold the precise value of either 5.55, 3.14 or 2.41, so you get an approximate answer.
To understand this better, try to write down the value of 1/3 as a decimal, when you only have limited space on the paper to write it. You'll end up with something like 0.33333
, which is an approximation of the actual value. The same happens to 5.55 when you write it in binary - it turns into 101.10001100110011001100110011...
which gets cut off somewhere to fit the space of the double.
import java.text.DecimalFormat;
double d = 5.55%3.14;
DecimalFormat df = new DecimalFormat("#.##");
System.out.println( df.format( d ));
Add DecimalFormat
Edit:
You can also
double d = 5.55%3.14;
System.out.printf("%1$.2f", d);
Java double can have precision issues.
Why don't you try BigDecimal
?
the reason is that java doesn't do math the way we do. java uses binary numbers (from chapter 4 of Horstmann's big java book) so to a computer, 435 = 4 * 10^2 + 3 * 10^1 + 5 * 10^0
it does this because binary numbers (1 or 0) are easier to manipulate since switches in the computer are either on or off (1 or 0).
this results in occassional rounding issues. if you want to force it to round, then do things like use a decimal format, or if you just need the displayed value rounded you can use String.format or printf