codelove
codelove

Reputation: 2016

how to make custom-data-attribute value numeric with javascript

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>

Upvotes: 6

Views: 12259

Answers (4)

Esailija
Esailija

Reputation: 140228

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.net/E7Av7/1/

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039200

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.net/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>​

Upvotes: 4

David Thomas
David Thomas

Reputation: 253416

Just use parseFloat():

var lon1 = parseFloat($('#zoom1').attr('data-lon1'));
   lat1 = parseFloat$('#zoom1').attr('data-lat1'));
console.log(lat1+lon1);

JS Fiddle demo.

References:

Upvotes: 6

ClarkeyBoy
ClarkeyBoy

Reputation: 5010

There is a JavaScript function called parseFloat. Use parseFloat($("#zoom1").attr("data-lon1").

Upvotes: 0

Related Questions