java - 在 Java 中将 double 转换为 String,反之亦然,而不会失去准确性

标签 java types

double 的字符串表示通过 写入文件和从文件中读取。 C# 应用。

C# 应用程序使用以下片段将 double 转换为字符串:

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

C# 应用程序使用以下片段将字符串转换为 double 值
double num = double.Parse(s, NumberStyles.Float, (IFormatProvider) NumberFormatInfo.InvariantInfo);

如果同一个文件被 写入和读取Java 应用程序,您将如何在不丢失数据的情况下转换类型?

最佳答案

只是使用 Double.parseDouble()Double.toString()我相信应该可以在不丢失数据的情况下工作。特别是,来自 Double.toString() 的文档:

How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.



另一种选择,如果你想保留精确的字符串表示(这不太一样)是使用 BigDecimal在 java 。

关于java - 在 Java 中将 double 转换为 String,反之亦然,而不会失去准确性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/755449/

相关文章:

java - java解析字符串以删除空格

java - 为什么在 Linux 上使用 Java Attach API 会失败? (即使 Maven 构建完成)

java - Java8-Streams 中的 GroupingBy

javascript - 在子组件中键入 useState setter

c - 变量类型信息如何以及在哪里存储?

java - 如何从字符串日期获取日、月、年?

java - eclipse 中的 "failed while installing axis2 core 1.1"?

Android:content://sms/"type"值的文档?

c++ - 如何在不使用开关的情况下随机选择一个类进行实例化?

c++ - 从缓冲区输入的位