I use google maps Api, in any cases I have value of Latitude and Longitude very long length, for example in Console:
results[0].geometry.location.lng()
-74.80111590000001
results[0].geometry.location.lat()
42.055163
I want to get max 7 chars after ma
results[0].geometry.location.lng().toString().substring(0,10)
"-74.801115"
but if the number is negative after ma is not 7 chars,.. for this I can to use indexOf('.') and get 7 chars after ma, but I have very much place where I need to get this values and I want to use something with less code any proposal?
I use google maps Api, in any cases I have value of Latitude and Longitude very long length, for example in Console:
results[0].geometry.location.lng()
-74.80111590000001
results[0].geometry.location.lat()
42.055163
I want to get max 7 chars after ma
results[0].geometry.location.lng().toString().substring(0,10)
"-74.801115"
but if the number is negative after ma is not 7 chars,.. for this I can to use indexOf('.') and get 7 chars after ma, but I have very much place where I need to get this values and I want to use something with less code any proposal?
Share Improve this question asked Jan 26, 2015 at 19:26 AlexAlex 9,74030 gold badges107 silver badges166 bronze badges3 Answers
Reset to default 9It appears that your lat and long are numbers (if not, there may be better options). Numbers in JS have the toFixed()
method to convert them into strings with a given number of decimal places.
In your case, (-74.80111590000001).toFixed(7)
should return the string "-74.8011159"
, which I believe is what you want. It will also round correctly, which substring
is not capable of (not being aware of how numbers work).
lodash v3.0.0 has been released with new String
options last week.
You could use the new trunc
function:
trunc
Truncates string if it is longer than the given maximum string length. The last characters of the truncated string are replaced with the omission string which defaults to "…".
https://lodash./docs#trunc
Example:
_.trunc('-74.80111590000001', 7); // -74.801
This is a more flexible and generic approach, so one function can be reused throughout a script for the purpose of rounding a number to a given number of decimal places.
function roundNumber(value, decimals){
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
And to use...
var rounded_lng = roundNumber(results[0].geometry.location.lng(), 7);
var rounded_lat = roundNumber(results[0].geometry.location.lat(), 7);