在Java中将双精度型转换为String,反之亦然,将精度转换为String [英] Convert a double to a String in Java and vice versa without losing accuracy

查看:50
本文介绍了在Java中将双精度型转换为String,反之亦然,将精度转换为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#应用程序将 double String 表示写入文件或从文件中读取.

A String representation of a double is written to and read from a file by a C# application.

C#应用程序使用以下片段将双精度型转换为字符串:

The C# application converts the double to a string using the following fragment:

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

C#应用程序使用以下片段将字符串转换为双精度

The C# application converts the string to a double using the following fragment

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

如果要在 Java 应用程序中写入和读取同一文件,您将如何转换类型而不丢失数据?

If that same file were to be written to and read from by a Java application, how would you go about converting the types without losing data?

推荐答案

只需使用 Double.parseDouble() Double.toString()即可正常工作,而不会丢失数据,我相信.特别是,从 Double.toString():

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

必须打印多少位数m或a的小数部分?那里必须至少为一位数字代表小数部分,并且除此之外,还有很多,唯一所需的更多数字从中区分参数值类型double的相邻值.那是,假设x是精确的由由产生的十进制表示有限非零的此方法d.则d必须是双精度最接近x的值;或者如果两个双值相等地接近x,然后是d必须是其中之一,并且最少显着意义的d必须为0.

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.

如果要保留确切的字符串表示形式(这不太一样),另一种选择是在Java中使用 BigDecimal .

Another alternative, if you want to preserve the exact string representation (which isn't quite the same thing) is to use BigDecimal in Java.

这篇关于在Java中将双精度型转换为String,反之亦然,将精度转换为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆