Tinus Erasmus
Tinus Erasmus

Reputation: 15

issue with .toFixed() results

Good day,

I am still learning JS and HTML and I noticed something quite interesting for me

I am using Google Geocoding scripts and created an on click event on the map to retrieve the GPS co-ordinates,

 function onClickCallback(event){
    var str = event.latLng.toString().slice(1,-1).split(',', 2);
    var lat1 = parseFloat(str[0]).toFixed(5);
    var lng1 = parseFloat(str[1]).toFixed(5);
    var latlng1 = new google.maps.LatLng(lat1,lng1).toString().slice(1,-1);

    document.getElementById('latlng').value = latlng1;

this works perfectly for my needs however for some odd reason the second part "lng1" does not round down as expected and as an example the below is the result

-25.3341, 27.64984000000004 or -25.34403, 27.97393999999997

as the first part 'lat1' works fine what is the reason or cause for the second part 'lng1' not rounding and only displaying the first 5 decimals and how can I fix it

Upvotes: 0

Views: 179

Answers (1)

Peter Herdenborg
Peter Herdenborg

Reputation: 5962

The problem is most likely a combination of type conversion and javascript's built in floating point number representation.

When you call toFixed() your number is actually converted to a string with the desired number of decimals. google.maps.LatLng() expects two numbers but, since you're not getting any errors, is also fine receiving string representations of numbers instead.

Internally, I assume google.maps.LatLng() converts the lat1 and lng1 arguments to numbers again. Since the way javascript represents numbers often results in small rounding errors, the toString() gets lng1, which is now a number again and likely slightly different than what toFixed() originally returned, and converts it back to a string.

If you want to be able to output nice numbers, you could postpone the toFixed() calls until the end:

...
var lat1Formatted = parseFloat(latlng1.split(', ')[0]).toFixed(5);
var lng1Formatted = parseFloat(latlng1.split(', ')[1]).toFixed(5);

document.getElementById('latlng').value = lat1Formatted + ', ' + lng1Formatted;

Upvotes: 1

Related Questions