繁体   English   中英

是否可以通过字符串格式化程序以比浮点数更高的精度显示双精度数?

[英]Is it possible to display double with larger precision than a float via String Formatter?

在 Java 中使用双精度时如何保持精度? 我有以下测试用例:

double x = -1.0 / 3.0;
double y = 1.0000000001;
Point2 p = new Point2(x, y);

String expected = "(" + x + ", " + y + ")";
assertEquals(expected, p.toString());

Point2 构造函数:

public Point2(double x, double y) {
  this.x = x;
  this.y = y;
  }

toString 覆盖:

@Override
public String toString() {
  return String.format("(%f, %f)", this.x, this.y);
}

这是失败的: org.junit.ComparisonFailure: expected:<(-0.333333[3333333333, 1.0000000001])> but was:<(-0.333333[, 1.000000])>

问题出在我的 toString() 方法中。 它们现在被格式化为浮点数是有道理的。 最终将其更新为:

@Override
public String toString() {
    return "(" + this.x + ", " + this.y + ")";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM