Convert double strings to Java and vice versa without losing precision

The string representation of the double is written to and read from the file using the C # application.

A C # application converts double to string using the following snippet:

value.ToString("R", NumberFormatInfo.InvariantInfo); 

C # application converts a string to double using the following snippet

 double num = double.Parse(s, NumberStyles.Float, (IFormatProvider) NumberFormatInfo.InvariantInfo); 

If the same file were to be written and read using a Java application, how could you convert types without losing data?

+2
source share
5 answers

Just using Double.parseDouble() and Double.toString() should work without data loss, I believe. In particular, from the docs for Double.toString() :

How many digits should be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and besides, as many, but only as many, more digits are needed to uniquely distinguish the value of an argument from adjacent values โ€‹โ€‹of type double. What Suppose that x is an exact mathematical value, represented by a decimal representation, created by this method for a finite nonzero argument d. Then d should be the double value closest to x; or if two double values โ€‹โ€‹are equally close to x, then d must be one of them and the least significant part of the significance of d must be 0.

Another alternative, if you want to preserve the exact string representation (which is not exactly the same), is to use BigDecimal in Java.

+12
source

Parts have limited precision and may not keep the string intact. The BigDecimal class has an arbitrary precession and saves a sring representation.

To convert a string to BigDecimal:

 BigDecimal d = new BigDecimal("10.1234567890"); 

Converting BigDecimal to string:

 System.out.println(d.toString()); 

More details here: http://epramono.blogspot.com/2005/01/double-vs-bigdecimal.html

+6
source

Do you need a string representation for any purpose, or is it intended only for transmitting textual data (for example, SOAP / REST messages)?

For the latter, you can convert a double value to a long one using java.lang.Double.doubleToRawLongBits(double value) and return to a double one using java.lang.Double.longBitsToDouble(long value) . You can wrap a long value as a string with hexadecimal encoding.

http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Double.html#doubleToRawLongBits(double) http://java.sun.com/j2se/1.5.0/docs/ api / java / lang / Double.html # longBitsToDouble (long)

This will keep the exact 64-bit double value that you have, but it will not be human readable (for most !;)).

+4
source

You just have to use the Java Double wrapper class, which is the capital of the "D", "Double"

int String s = Double.toString (yourDoubleVariable);

0
source

Double to line:

 String stringValue = Double.toString(value); 

String to double

 double doubleValue = Double.valueOf(value); 
0
source

All Articles