Output form and possible problems in Java floats

xiaoxiao2021-03-06  154

Recently, a database SQL statement is used in the project. This SQL statement is dynamically generated, similar to the following way: double quantity = ...; string SQL = "INSERT INTO" TABLENAME "(ID, Name, Quantity) VALUES (" ID ", '" Name " "" Quantity ")"; the system is running normally more than 1 year, and suddenly the system is wrong. Due to the lack of sufficient debugging information, commissioning is very difficult due to the lack of sufficient debugging information. After hard tracking and debug output, it is found that problems appear on the Double type Quantity string representation. Because Quantity in the recent system encountered a relatively large value (more than 10), the Double type quantity analysis was analyzed in the form of "1.153E7" scientific counting, although most SQL compatible drivers basically I know the form of digital representation of this scientific counting method, but there are still some do not support (if there is a regulation in the SQL specification, I don't know, welcome to find out). For some drivers that do not support this number representation, the problem is coming out, it will regard it as an illegal number to report an error. Floating points in Java include basic float, double, and object packaging type FLOAT and DOUBLE, for these floating point numbers, whether it is explicitly or implicitly calling toString () gets its representation string, output format All are performed in accordance with the following rules:?

If the absolute value is greater than 0.001, less than 10000000, then it is expressed in a conventional decimal form. • If the scientific count method is expressed. That is, similar to 1.234E8 form.

Clear these, you can avoid some problems, in addition, for most enterprise applications, users prefer to use ordinary decimal representations, rather than scientific counting forms, so they often encounter in actual projects. Unifying the Number of Java is unified as an ordinary decimal form, you can use java.text.decimalformat to convert, for example, convert Double type to retain 4 decimal point output: DECIMALFORMAT DF = New DecalogMAlFormat ("# .0000 "); Double D = 12345678.12345; String DSTR = DF.Format (D); this DSTR has become: 1234567.1234, not: 1.234567812345e7. Learn about the output of floating point numbers in Java, it is very important to keep in mind, especially for some enterprise applications for ordinary users, pay attention to formatting floating point numbers in an appropriate place. For some SQL drives, it is necessary to identify whether this scientific counting form is identified. Otherwise, it is equal to buried a non-time bomb to the system. When I explode, I don't know, maybe it is after a few years, then then it is then Looking for problems, the amendment process will become very difficult.

转载请注明原文地址:https://www.9cbs.com/read-127463.html

New Post(0)