Example Analysis of NumberFormat formatting float Type bug in Java
Editor to share with you the Java NumberFormat format float type bug example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!
First of all, this NumberFormat class can format all kinds of numbers. As long as you set it up a little bit, the result is still very rational.
However, he has such a lost bug, I don't know if you know?
/ * 2.3F has been formatted to 2.99. What the fuck. * in the case of the float type, the value is 2.3, but once it becomes Double, the value becomes 2.99999. * the parameter to this format is of type double. So, when you pass in parameters, you operate on 2.299999952316284. The result is 2.99 * / private static void floatFormatTest () {float responseTime = 2.3F; NumberFormat formatter; formatter = NumberFormat.getNumberInstance (); formatter.setGroupingUsed (false); formatter.setRoundingMode (RoundingMode.FLOOR); formatter.setMaximumFractionDigits (2); String format = formatter.format (responseTime); System.out.println (format); float v = Float.parseFloat (formatter.format (responseTime)); System.out.println (v);}
When you take a look at debug, what is the unexpected change in this number?
At this time, it is still OK. It's still normal.
See, this 2.3F float number automatically becomes double when it passes through format. Then it becomes unstable.
After the trade-off, 2.3 becomes 2.29.
How to avoid this problem
When using this BigDecimal, pass the parameter, pass the string. Otherwise, it's still not accurate.
The above is all the content of the article "sample Analysis of NumberFormat formatting float Type bug in Java". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!