Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 334
codelove Avatar asked Dec 27 '22 22:12

codelove


1 Answers

Just 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().
like image 165
David Thomas Avatar answered Dec 29 '22 12:12

David Thomas