1

I am looking to round the DistanceInput.value and DistanceInput1.value to 2 Decimals such as 1.80 and/or 11.80 etc...

Thanks

directionsService.route(request, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay.setDirections(response);
    distanceInput.value = response.routes[0].legs[0].distance.value / 1000 * 0.62137119;
    distanceInput1.value = response.routes[0].legs[0].distance.value / 1000 * 0.62137119 + 1.00;
  }
}
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
StuckonPHP
  • 11
  • 4

3 Answers3

2

Use .toFixed() method

var num = response.routes[0].legs[0].distance.value / 1000 * 0.62137119;
distanceInput.value = num.toFixed(2);

See more:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

Marcos Pérez Gude
  • 21,869
  • 4
  • 38
  • 69
  • I know the OP is asking about two decimals. This is just a warning for others who need more precision: `(0.3).toFixed(17) === "0.29999999999999999"` and `(0.1+0.2).toFixed(17) === "0.30000000000000004"` http://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Ruan Mendes Dec 14 '15 at 15:02
  • This has worked, Thanks for that. I will edit the post as i am struggling outputting it to PHP – StuckonPHP Dec 14 '15 at 15:21
1

Depends on the accuracy you need.

function toTwo() {    
    return +(Math.round(number + "e+2")  + "e-2");
}

or

Math.round(num * 100) / 100

Found another helpful one, if the float is a text.

If String

parseFloat(num).toFixed(2);

If Number

num = num.toFixed(2);
iDeal
  • 53
  • 2
  • 8
0

You can use (valueToRound).toFixed(2);

e.g. distanceInput.value = (response.routes[0].legs[0].distance.value / 1000 * 0.62137119).toFixed(2);

Moby
  • 650
  • 6
  • 11