Java浮点数学 - (转换为英尺/米)

Goi*_*arn 3 java floating-point

我认为非常基本的问题 - 我正在执行此功能:

private double convertMetersToFeet(double meters)
{
  //function converts Feet to Meters.
      double toFeet = meters;
      toFeet = meters*3.2808;  // official conversion rate of Meters to Feet
      return toFeet;
}
Run Code Online (Sandbox Code Playgroud)

问题是输出; 例如,我从101的输入得到337.36080000000004.截断浮点的适当做法是什么?

如下面的答案所假设,我希望4个有效数字与我的转换率保持一致.

Seb*_*ndt 8

您可以使用NumberFormat实例.

NumberFormat nf = NumberFormat.getInstance(Locale.UK);
nf.setMinimumFractionDigits(4);
nf.setMaximumFractionDigits(4);
System.out.println(nf.format(feet));
Run Code Online (Sandbox Code Playgroud)

或者您可以使用DecimalFormat.

DecimalFormat df = new DecimalFormat("0.0000");
System.out.println(df.format(feet));
Run Code Online (Sandbox Code Playgroud)

后者(DecimalFormat)将在您明确要声明格式时使用,而前者(NumberFormat)则需要本地化设置时使用.

对于四个一致的小数,如果您没有长距离工作,则无需拖动BigDecimal.