Pietro said:
Hi, thie is my simple test case:
public class Main {
public static void main(String[] args) {
float a = 123.76f;
float b = 52.0f;
System.out.println(a + b);
System.out.println((float) a + b);
System.out.println((float) a + (float) b);
System.out.println((float) (a + b));
}
}
The results for all four System.out is the same, guess what?:
175.01001
Cuold anyone explein me why, at least a refer to rules explaining what
happens?
Regards
It works if I declare primitive types as double.
iis it a strange causality or is a rule?
It "works" with float, too. It just doesn't work in the way that you
expect it to.
Computers use binary arithmetic. Some computers have used binary
arithmetic since the early 1950s, and nearly all computers have used
binary arithmetic since the mid 1960s. If you have taken any kind of
computer programming course at all, you should bring a lawsuit against
the fool of a teacher who did not instruct you in this.
Do you remember how, with decimal fractions, you discovered that 1/3 +
1/3 + 1/3 added up to 0.99 instead of 1? Well, with binary fractions,
you have the same problem where 1/10 or 1/100 is involved. But for
purposes of science and engineering, binary arithmetic is just as
effective as decimal arithmetic, and faster and cheaper. The world is
not carved up into exact decimal fractions. Distances between points are
not always an exact number of millimeters. Masses of objects are not
always an exact number of grams. Time intervals are not always an exact
number of milliseconds.
Money, on the other hand, /is/ carved up into exact decimal fractions.
Therefore, when you are working with money, you should use the Java
BigDecimal class, instead of float or double. Dollars are always an
exact number of cents. Euros are always an exact number of eurocents.
Pounds are always an exact number of new pence. The considerable loss of
time involved in using BigDecimal is unimportant, because the
calculations involving money are far less intensive than the complex
problems in calculus that come up in science and engineering.