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