Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java floating point math - (conversion for feet/meters)

Pretty basic question I think - I'm performing this function:

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;
}

Problem is the output; for example I get 337.36080000000004 from an input of 101. What's the appropriate practice for truncating the floating points?

As the answers below assumed, I'd want 4 significant figures to remain consistent with my conversion ratio.

like image 381
GoingTharn Avatar asked Sep 12 '26 02:09

GoingTharn


2 Answers

You can use a NumberFormat instance.

NumberFormat nf = NumberFormat.getInstance(Locale.UK);
nf.setMinimumFractionDigits(4);
nf.setMaximumFractionDigits(4);
System.out.println(nf.format(feet));

Or you can use DecimalFormat.

DecimalFormat df = new DecimalFormat("0.0000");
System.out.println(df.format(feet));

The latter (DecimalFormat), is to be used when you explicitly want to state the format and the former (NumberFormat), when want localized settings.

For four consistent fractional figures, there is no need to drag in BigDecimal, if your aren't working with really long distances.

like image 93
Sebastian Ganslandt Avatar answered Sep 14 '26 15:09

Sebastian Ganslandt


I'm answering my own question for posterity's sake. I used the DecimalFormat answer above, but the answers failed to take into account the return type of the method.

Here's the finished code:

  private double convertMetersToFeet(double meters)
{
  //function converts Feet to Meters.
      double toFeet = meters;
      toFeet = meters*3.2808;  // official conversion rate of Meters to Feet
      String formattedNumber = new DecimalFormat("0.0000").format(toFeet); //return with 4 decimal places
      double d = Double.valueOf(formattedNumber.trim()).doubleValue();
      return d;
}
like image 42
GoingTharn Avatar answered Sep 14 '26 17:09

GoingTharn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!