Converting a string to double always leads me to the wrong representation

I want to convert this string "0.00071942446044" to double using the Double.parsedouble method, but always gives this answer 7.1942446044E-4

Is there any idea to convert it to double, but keeping the same number as in the string?

+4
source share
3 answers

You can use new BigDecimal(myString) , this is not the same thing, but will keep the same view. It provides an API for performing various mathematical calculations, but slower than performing arithmetic operations with doubles.

+3
source

Although both numbers are the same, you can use DecimalFormat to control the format as you like, just for presentation purposes. Here is an example:

 String s = "0.00071942446044"; Double d = Double.parseDouble(s); DecimalFormat df = new DecimalFormat("#.##############"); System.out.println("double: " + d); System.out.println("formatted: " + df.format(d)); 

Output:

 double: 7.1942446044E-4 formatted: 0.00071942446044 

Note that the number after the decimal point exactly matches your example.

+3
source

This is just another way to display the number. Documentation does a reasonable job of explaining it.

If you just want to print it in the same format, you can use printf or String.format :

Print 0.000719 :

 System.out.printf("%f\n", Double.parseDouble("0.00071942446044")); 

Print 0.00071942446044 : (with hard-coded precision, which is probably not an idea)

 System.out.printf("%.14f\n", Double.parseDouble("0.00071942446044")); 

Also note that numbers are not stored in terms of numbers, so you won’t get an accurate representation with high precision for floating point types ( float and double ) (although double , as you can see, can handle this number of digits). Note what happens if you use float :

Print 7.1942444 :

 System.out.printf("%.7f\n", Float.parseFloat("7.1942446")); 

Similar test case for double : (prints 7.1942446044352310 )

 System.out.printf("%.16f\n", Double.parseDouble("7.1942446044352312")); 

If you need more accuracy (for the price, obviously memory and speed), you should use BigDecimal .

+1
source

Source: https://habr.com/ru/post/1481195/


All Articles