Why can't you switch on floats in Java? [duplicate] - java

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 9 years ago.
Could you please explain, why I got next result:
when I run this:
System.out.println((0.2 - 0.1));
I got: 0.1
when I run this:
System.out.println((0.3 - 0.2));
I got: 0.09999999999999998
I know that number "0.1" doesn't have finite representation in binary, but it doesn't explain the results above. Most likely this is not about particular language but about how digits are stored in computer.

Java uses IEEE floating point to represent double values. It is not a precise representation, and some calculations result in tiny errors that manifest themselves in this way.

I agree with Bohemian above (float and double is not precise) so you will get oddities like this
but there is a solution for your problem:
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(1);
nf.format(0.3f - 0.2f);
This will produce 0.1.

Related

How to get the value without round up/down in Java? [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
double d0 = Double.parseDouble("53.82233040000000557");
double d1 = Double.valueOf("53.82233040000000557");
output
d0 = 53.822330400000006
d1 = 53.822330400000006
Precision Numbers in Java
Class java.math.BigDecimal is better for handling numbers where precision matters (like monetary amounts), see BigDecimal VS double.
It could be used for geo-coordinates (latitude/longitude). Although practitionars argue that double is precise enough for lat./long. - since you don't want to locate something at nano-meter scale.
Example Code
If you need high precision and scale for your number, use BigDecimal like this:
BigDecimal decimalValue = new BigDecimal("53.82233040000000557");
System.out.println("as BigDecimal: " + decimalValue.toPlainString());
// prints exactly: 53.82233040000000557
Run this code online (IDE one): Double VS BigDecimal for high precision
Read more
Read more in a tutorial on Java: BigDecimal and BigInteger
If you need precision, you have to use a BigDecimal.
The answer is that you cannot. The values you are getting are the most accurate approximation to your values that can possibly be stored in a double. There is no possible way to get a more accurate, less rounded value stored in a double.
If you require that the answers are not rounded at all, therefore, you should not be using double. The data type you should be using instead is BigDecimal.

Java Modulus 1 (%1) returns approximate value [duplicate]

This question already has answers here:
Why are floating point numbers inaccurate?
(5 answers)
Closed 6 years ago.
I've got sample code
double k=3.14, l=0.5, m=1.3333;
System.out.println(k+":"+k%1);
System.out.println(l+":"+l%1);
System.out.println(m+":"+m%1);
which results in output:
3.14:0.14000000000000012
0.5:0.5
1.3333:0.33329999999999993
Why is it so? I expected x%1 to return non-integer part of the value of x?
See Is floating point math broken?
Binary floating point math is like this. In most programming languages, it is based on the IEEE 754 standard. JavaScript uses 64-bit floating point representation, which is the same as Java's double. The crux of the problem is that numbers are represented in this format as a whole number times a power of two; rational numbers (such as 0.1, which is 1/10) whose denominator is not a power of two cannot be exactly represented.

double operation wrong answer in Java [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 6 years ago.
I have 2 numbers stored as Double, 1.4300 and 1.4350. When I subtract 1.4350 - 1.4300, it gives me the result: 0.0050000000000001155. Why does it add 1155 to the end and how can I solve this so that it returns 0.005 or 0.0050? I'm not sure rounding will work as I'm working with 2 and 4 decimal numbers.
Oh, I love these... these are caused by inaccuracy in the double representation and floating-point arithmetic is full of these. It is often caused by recurring numbers in binary (i.e. base-2 floating-point representation). For example, in decimal 1/3 = 0.3333' In binary 1/10 is a recurring number, which means it cannot be perfectly represented. Try this: 1 - 0.1 - 0.1 - 0.1 - 0.1. You wont get 0.6 :-)
To solve this, use BigDecimal (preferred) or manipulating the double by first multiplying it something like 10000, then rounding it and then dividing it again (less clean).
Good question... it has caused huge problems in the past. Missiles overshooting targets, satellites crashing after launch, etc. Search the web for some, you'll be amazed!
This is a common pitfall with some computer representations of fractional numbers, see this question or google for floating point precision.
Double is not the right type for very precision floating point calculations, if you want exact results you have to use BigDecimal.

Adding and subtracting doubles are giving strange results [duplicate]

This question already has answers here:
Retain precision with double in Java
(24 answers)
Closed 9 years ago.
So when I add or subtract in Java with Doubles, it giving me strange results. Here are some:
If I add 0.0 + 5.1, it gives me 5.1. That's correct.
If I add 5.1 + 0.1, it gives me 5.199999999999 (The number of repeating 9s may be off). That's wrong.
If I subtract 4.8 - 0.4, it gives me 4.39999999999995 (Again, the repeating 9s may be off). That's wrong.
At first I thought this was only the problem with adding doubles with decimal values, but I was wrong. The following worked fine:
5.1 + 0.2 = 5.3
5.1 - 0.3 = 4.8
Now, the first number added is a double saved as a variable, though the second variable grabs the text from a JTextField. For example:
//doubleNum = 5.1 RIGHT HERE
//The textfield has only a "0.1" in it.
doubleNum += Double.parseDouble(textField.getText());
//doubleNum = 5.199999999999999
In Java, double values are IEEE floating point numbers. Unless they are a power of 2 (or sums of powers of 2, e.g. 1/8 + 1/4 = 3/8), they cannot be represented exactly, even if they have high precision. Some floating point operations will compound the round-off error present in these floating point numbers. In cases you've described above, the floating-point errors have become significant enough to show up in the output.
It doesn't matter what the source of the number is, whether it's parsing a string from a JTextField or specifying a double literal -- the problem is inherit in floating-point representation.
Workarounds:
If you know you'll only have so many decimal points, then use integer
arithmetic, then convert to a decimal:
(double) (51 + 1) / 10
(double) (48 - 4) / 10
Use BigDecimal
If you must use double, you can cut down on floating-point errors
with the Kahan Summation Algorithm.
In Java, doubles use IEEE 754 floating point arithmetic (see this Wikipedia article), which is inherently inaccurate. Use BigDecimal for perfect decimal precision. To round in printing, accepting merely "pretty good" accuracy, use printf("%.3f", x).

Getting numbers after decimal Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Strange floating-point behaviour in a Java program
Why does JSP/JSTL division by 1000 sometimes give remainder?
I am trying to get the numbers after the decimal.
ex: 60.4 -> 0.4
Yet, when do
double a = 60.4 % 1;
it comes out to be 0.3999999999999986.
Why is this? And how could it be fixed?
Use fixed-point types
BigDecimal src = new BigDecimal("60.4");
BigDecimal a = src.remainder(BigDecimal.ONE);
You can use DecimalFormat to do your desired task.
OK here is how you can do: How to get the numbers after the decimal point? (java)
I think this is exactly what you are looking for. So essentially you can use:
double x = d - Math.floor(d);
OR
BigDecimal class for exact digits after decimal.

Categories

Resources