Hi I am reading two numbers from html data-tags stored in a div. When I try to add the numbers together they are appended as strings. Is there anyways to include numbers in a data attribute and access them as numbers or convert them back into non - string numbers with javascript thanks.
Example
<div data-Lon1="1.3" data-Lat1="-1.2"></div>
<script>
lon1 = $('#zoom1').attr('data-lon1');
lat1 = $('#zoom1').attr('data-lat1');
console.log(lat1+lon1);
//returns '1.3-1.2' (I want .1 in this example)
</script>
Hi I am reading two numbers from html data-tags stored in a div. When I try to add the numbers together they are appended as strings. Is there anyways to include numbers in a data attribute and access them as numbers or convert them back into non - string numbers with javascript thanks.
Example
<div data-Lon1="1.3" data-Lat1="-1.2"></div>
<script>
lon1 = $('#zoom1').attr('data-lon1');
lat1 = $('#zoom1').attr('data-lat1');
console.log(lat1+lon1);
//returns '1.3-1.2' (I want .1 in this example)
</script>
Share
Improve this question
asked Jun 25, 2012 at 21:09
codelovecodelove
2,0165 gold badges27 silver badges37 bronze badges
2
- 1 An easier way to access data attributes you can use is this btw: $("zoom1").data("lon1"); – Logard Commented Jun 25, 2012 at 21:12
- for some reason trying to access the data with the data method returns undefined. Does this only work if you store the data with the data method as well? – codelove Commented Jun 25, 2012 at 21:22
4 Answers
Reset to default 6Just use parseFloat()
:
var lon1 = parseFloat($('#zoom1').attr('data-lon1'));
lat1 = parseFloat$('#zoom1').attr('data-lat1'));
console.log(lat1+lon1);
JS Fiddle demo.
References:
number()
.parseFloat()
.
You could use the .data()
method which will take care of properly parsing the value to the underlying type:
var lon1 = $('#zoom1').data('lon1');
var lat1 = $('#zoom1').data('lat1');
console.log(lat1 + lon1);
You will notice that when using the .data()
method you are no longer passing as argument the full attribute name, but only the suffix - lon1
and lat1
instead of data-lon1
and data-lat1
.
And here's a live demo: http://jsfiddle/E7Av7/
Oh, and don't forget to give a correct id to your div so that your data selector returns something as you seem to have forgotten to do this in the code snippet posted in your question:
<div data-Lon1="1.3" data-Lat1="-1.2" id="zoom1"></div>
There is a JavaScript function called parseFloat
. Use parseFloat($("#zoom1").attr("data-lon1")
.
Use .data()
which attempts to parse the value.
var lon1 = $('div').data('lon1');
var lat1 = $('div').data('lat1');
console.log(lat1+lon1);
If you want the result to be 0.1
from that though, you must do something like:
console.log( Math.round( ( lat1+lon1 ) * 100000000000 ) / 100000000000 );
Otherwise you will get 0.10000000000000009
instead of 0.1
See Is floating point math broken?
http://jsfiddle/E7Av7/1/