Java序列化双精度

Java序列化双精度,java,serialization,double,Java,Serialization,Double,我想将double序列化/反序列化为可读字符串。我很高兴在第6个dp之后失去任何准确性 做这件事的正确方法是什么 我关心的是System.out.println(1.03-.42)打印0.610000000000001,而不是0.61 Thxs.查看和。查看和。最简单的方法是使用PrintWriter和BufferedReader double[][] doubles = new double[10][10]; for(double[] ds : doubles) for(int i=0

我想将double序列化/反序列化为可读字符串。我很高兴在第6个dp之后失去任何准确性

做这件事的正确方法是什么

我关心的是System.out.println(1.03-.42)打印0.610000000000001,而不是0.61


Thxs.

查看和。

查看和。

最简单的方法是使用PrintWriter和BufferedReader

double[][] doubles = new double[10][10];
for(double[] ds : doubles)
    for(int i=0;i<ds.length;i++)
        ds[i] = Math.random() * 100;

PrintWriter pw = new PrintWriter("double.tsv");
for(double[] ds : doubles) {
    for(double d: ds)
        pw.printf("%.6f\t", d);
    pw.println();
}
pw.close();

BufferedReader br = new BufferedReader(new FileReader("double.tsv"));
String line;
while((line = br.readLine())!=null) {
    String[] words = line.split("\t");
    for (String word : words) {
        double d = Double.parseDouble(word);
        System.out.print(d+"\t");
    }
    System.out.println();
}

最简单的方法是使用PrintWriter和BufferedReader

double[][] doubles = new double[10][10];
for(double[] ds : doubles)
    for(int i=0;i<ds.length;i++)
        ds[i] = Math.random() * 100;

PrintWriter pw = new PrintWriter("double.tsv");
for(double[] ds : doubles) {
    for(double d: ds)
        pw.printf("%.6f\t", d);
    pw.println();
}
pw.close();

BufferedReader br = new BufferedReader(new FileReader("double.tsv"));
String line;
while((line = br.readLine())!=null) {
    String[] words = line.split("\t");
    for (String word : words) {
        double d = Double.parseDouble(word);
        System.out.print(d+"\t");
    }
    System.out.println();
}

如果您想将该值用于测试目的,Double.toString(Double)可能会很好

如果您想要更可读的数字(例如,1.01而不是1.01000000000587732),可以使用DecimalFormat(http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html)或大十进制:

BigDecimal bd = BigDecimal.valueOf(double)
BigDecimal bd2 = bd.setScale(6, RoundingMode.HALF_UP); // six decimal
String out = bd2.toString();
String out2 = bd2.toPlainString();
编辑:在用户编辑之后,我认为正确的方法是:

    DecimalFormat df = new DecimalFormat("0.00");
    System.out.println(df.format(1.03 - .42));

如果您想将该值用于测试目的,Double.toString(Double)可能会很好

如果您想要更可读的数字(例如,1.01而不是1.01000000000587732),可以使用DecimalFormat(http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html)或大十进制:

BigDecimal bd = BigDecimal.valueOf(double)
BigDecimal bd2 = bd.setScale(6, RoundingMode.HALF_UP); // six decimal
String out = bd2.toString();
String out2 = bd2.toPlainString();
编辑:在用户编辑之后,我认为正确的方法是:

    DecimalFormat df = new DecimalFormat("0.00");
    System.out.println(df.format(1.03 - .42));

您想序列化具有双精度值的对象,或者只是将双精度值解析为字符串并将字符串返回双精度值?关注的是无法在FP中表示的数字。您想序列化具有双精度值的对象,或者只是将双精度值解析为字符串并将字符串返回双精度值?关注的是无法在FP中表示的数字外交政策。