Java floating point - (conversion for feet / meters)

Pretty simple question, I think - I am 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;
}

The problem is the exit; for example, I get 337.36080000000004 from input 101. What is the appropriate practice for truncating floating points?

As follows from the answers below, I would like 4 significant digits to remain in accordance with my conversion rate.

+3
source share
5 answers

You can use the 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));

(DecimalFormat) , (NumberFormat), .

BigDecimal, .

+8

. DecimalFormat , .

:

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

, BigDecimal float. , DecimalFormat.

DecimalFormat df = new DecimalFormat ("0.00");
System.out.println(df.format(convertMetersToFeet(101)));
+1

java.math.BigDecimal .

0

If this is not for printing, you should not care about the error. 337.36080000000004 is exactly the same as 337.3608, since you have only 5 significant digits in the coefficient and only 3 in the test input. (And I certainly hope the answer to your method gave 331, not 337)

However, this line, derived from another question , seems to do the trick too.

double toFeet = ((int)(meters*3.2808*10000))/10000.0;

The only problem is that overflow is much faster.

0
source

Source: https://habr.com/ru/post/1704222/


All Articles