I kinda grasp that floating-point numbers have some issue with a rounding error, but I was hoping someone may be able to give me a more in-depth explanation as to why the floating-point type is not allowed in switch statements.
Asked
Active
Viewed 26 times
0
-
It's done for very good reason -- equality is a darn tricky thing to come by with floating point numbers. – Hovercraft Full Of Eels Jan 24 '16 at 03:20
-
2You've essentially answered yourself. Floats aren't 100% precise. So you switch on `0.3` but your float value is `3/10=0.3000000000001` and your `case` doesn't work. Disclaimer: I made up the values. This is just an example. – Arc676 Jan 24 '16 at 03:21
-
yeah I get that but, why? Like if I set a variable to 7.000 what actually happens in memory? What is ACTUALLY stored? – A.Jarrett Jan 24 '16 at 03:22
-
This has been asked so many times, please study the many duplicates out there. Also look [here](http://programmers.stackexchange.com/questions/256185/how-is-a-floating-point-number-represented-in-java). – Hovercraft Full Of Eels Jan 24 '16 at 03:26
-
Since floats take up 32 bits, just like ints, you could switch on them. `switch (Float.floatToIntBits(myFloat)) {`. But you need to pre-calculate the values for the case statements since they need to be constant and a call to Float.floatToIntBits is not constant. (And it's a very bad idea, given the complexities of floating point representations and accumulating errors during floating point calculations) – Erwin Bolwidt Jan 24 '16 at 03:35
-
Not sure I see why this is a duplicate of the question it's marked a duplicate of. The linked question concerns number representation. Since it's possible to specify a `float` exactly in your source code, why shouldn't you be able to switch on `float` values? (My next question: why would you ever want to?) – tmyklebu Jan 24 '16 at 15:20