我想将双精度序列化/反序列化为可读的字符串。我很高兴在第6 dp之后失去任何准确性。
这样做的正确方法是什么?
我担心System.out.println(1.03 - .42)打印0.6100000000000001而不是0.61。
Thxs。
答案 0 :(得分:2)
如果您希望将值用于测试目的,Double.toString(double)可能会很好。
如果你想要一个更可读的数字(例如1.01而不是1.01000000000587732),你可以使用DecimalFormat(http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html )或BigDecimal:
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));
答案 1 :(得分:1)
答案 2 :(得分:-2)
最简单的方法是使用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();
}
打印
72.520491 85.341994 21.958533 48.914986 14.959155 54.398293 54.438528 6.265907 77.654032 94.363109
65.594713 66.943443 69.891651 3.62663 13.445234 3.281239 99.897356 53.072258 11.931774 83.802643
17.387541 56.598334 90.104328 69.379567 95.631605 34.931461 73.336693 21.300139 50.511963 79.326218
61.844333 20.076352 81.668206 69.500067 45.936303 80.639298 86.534122 51.031074 89.718252 89.510961
41.923934 31.450051 35.373463 82.607984 69.796802 11.387551 28.684281 28.524173 3.926274 27.390139
43.116206 81.455006 52.424004 46.399187 84.572294 20.368705 7.414759 18.389408 91.835487 96.594918
87.632357 63.293224 8.751766 70.693449 12.30385 41.090964 93.36716 31.281827 95.411907 29.825814
46.516716 53.442007 18.273036 15.306335 87.773823 72.392803 85.34191 78.388259 80.203328 19.306142
93.249744 50.981212 7.02211 90.461556 46.307283 0.304891 33.055868 98.374818 33.050704 92.423133
41.791121 84.102962 37.881277 80.713237 24.856496 53.619386 99.447379 62.681776 14.927559 37.969094