Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of NumberFormat formatting float Type bug in Java

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report