0

I am using following formula to convert feet to miles and miles to feet.

Before save in db I convert value from Feet to Miles and during fetch from db I convert it back to Feet. Both formula I have mentioned in below code part.

It works fine with round when I give exact number like 5280 Feet = 1 Miles but when I give some approx number like 6200 Feet it save 1.23 Miles in db and during fetch in convert like 6177.60 so it sound like there is problem in conversion because actual value change from 6200 to 6177.60.

Second problem If I remove round before saving database then it save 5280 Feet = 0.99999999792 miles in db and it create problem during back end calculation which need exact miles value and we can't apply round there.

So I am looking for solution which save exact conversion (like 5280 Feet = 1 Miles) in db and doesn't change feet value during fetch.

  convertFeetToMiles(feet) {
    return this.roundTo(feet * 0.000189393939, 5);
  }

  convertMilesToFeet(miles) {
    return this.roundTo(miles * 5280.0, 2);
  }

  roundTo(n, digits) {
    var negative = false;

    if (digits === undefined) {
      digits = 0;
    }
    if (n < 0) {
      negative = true;
      n = n * -1;
    }

    const multiplicator = Math.pow(10, digits);
    n = parseFloat((n * multiplicator).toFixed(11));
    n = (Math.round(n) / multiplicator).toFixed(2);
    if (negative) {
      n = (n * -1).toFixed(2);
    }

    return n;
  }
Pushkar Rathod
  • 353
  • 2
  • 7
  • 26
  • Possible duplicate of [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) – Igor Apr 17 '18 at 19:06
  • Personally I prefer [decimal.js](https://github.com/MikeMcl/decimal.js-light/). There is also a [light version](https://github.com/MikeMcl/decimal.js-light/) available. – Igor Apr 17 '18 at 19:08
  • @Igor No. My scenario is total different from which u mentioned. I want to round before save to db but also need same feet value during fetch. – Pushkar Rathod Apr 18 '18 at 15:25

1 Answers1

1

After all finally doing some R & D on conversion formula I got solution.

Simply I changed the formula and it's work like a charm.

The new formula is like as below.

convertFeetToMiles(feet) {
    return feet / 5280;
  }

  convertMilesToFeet(miles) {
    return Math.round(miles * 5280);
  }

Using this formula it gives me exactly miles value i.e 5280 Feet = 1 Mile and 1 Mile = 5280 during retrieve from db.

I hope this may help to someone who also look for same kind of solution.

Pushkar Rathod
  • 353
  • 2
  • 7
  • 26