admin管理员组文章数量:1327301
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);
本文标签: javascriptLatitude and Longitude limit max lengthStack Overflow
版权声明:本文标题:javascript - Latitude and Longitude limit max length - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742202452a2432215.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论