0

Hello I have the code for a mileage calculator and I want the displayed mileage to be rounded to one decimal place. What is the code for this?

Don't just say to round the 1609.3440006146921597227828997904 up because I want the calculated mileage to be as accurate as possible before it is rounded.

The code for my mileage calculator is below:

<html>
    <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">

    var directionDisplay;
    var map;


function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var copenhagen = new google.maps.LatLng(55.6771, 12.5704);
    var myOptions = {
        zoom:12,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: copenhagen
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
    }


    var directionsService = new google.maps.DirectionsService();

    function calcRoute() {
    var start = document.getElementById("start").value;
    var end = document.getElementById("end").value;
    var distanceInput = document.getElementById("distance");

    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            distanceInput.value = response.routes[0].legs[0].distance.value / 1609.3440006146921597227828997904;
        }
    });
    }
    </script>

    <title>Distance Calculator</title>

    <style type="text/css">

            body {
                font-family:Helvetica, Arial;
            }
            #map_canvas {
                height: 50%;
            }
    </style>
    </head>
    <body>

    <body onload="initialize()">
    <p>Enter your current location and desired destination to get the distance</p>
        <div>
            <p>
                <label for="start">Start: </label>
                <input type="text" name="start" id="start" />

                <label for="end">End: </label>
                <input type="text" name="end" id="end" />

                <input type="submit" value="Calculate Route" onclick="calcRoute()" />
            </p>
            <p>
                <label for="distance">Distance (miles): </label>
                <input type="text" name="distance" id="distance" readonly="true" />
            </p>

<p><a href="mailto:moniza@syedasadiq.co.uk?subject=Mileage&body="
   onclick="this.href += calcRoute('string', 'distance');"
>
Click to send email
</a></p>
        </div>
        <div id="map_canvas"></div>
    </body>
</html>

javascript google geolocation maps 
mr.soroush
  • 1,110
  • 2
  • 14
  • 31
Pancake_Senpai
  • 915
  • 5
  • 12
  • 19
  • 3
    Do you know about `Math.round(n)`? – Brigand Aug 03 '13 at 07:52
  • 1
    As FakeRainBrigand said you want to use [Math.round](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round) it can do precision and everything you need according to your question – abc123 Aug 03 '13 at 07:57
  • 1
    Math.round(num*10) //for one decimal pt –  Aug 03 '13 at 07:59

3 Answers3

3
var n = 1609.3440006146921597227828997904;

// Methods that JS provides
console.log(Math.round(n)); // 1609 (number)
console.log(n.toFixed(6)); // 1609.344001 (string)

// You can do this, if you prefer (but not recommended at all)
var round = function(n, d){
  return Math.round(n*Math.pow(10,d))/Math.pow(10,d);
};
console.log(round(n, 6)); // 1609.344001 (number)
JiminP
  • 2,136
  • 19
  • 26
  • Can you add more details on the formula in the round method? @JiminP – Ponpon32 Apr 04 '17 at 07:55
  • @YochaiAkoka It basically moves the decimal point to the right (`n*Math.pow(10,d)`), rounds, and moves the decimal point to the left(`/Math.pow(10,d)`) again. – JiminP May 10 '17 at 05:31
  • By the way, now I recommend `Number.prototype.toFixed` over this method. In almost all cases rounding to nth place happens when a number is displayed, and `toFixed` is _the_ method for this case. – JiminP May 10 '17 at 05:32
1

You should use Number.toFixed, you pass a parameter for how much digits you wish after the point:

var x = 23.142342341231;
console.log(x.toFixed(1));

After you get the fixed number all you should do is parseFloat.

Ponpon32
  • 2,150
  • 2
  • 15
  • 26
1

Math.round(num*10) will do the trick. But you may want to keep the original number for further processing in order to avoid rounding precision errors.

Does that help?

AlexGrafe
  • 8,292
  • 1
  • 15
  • 12