One way of doing it is removing the quotes:
<script>
var val = <?php echo $val; ?>;
</script>
But there may be edge cases in which php yields unexpected results, so in my opinion it's a good practice to keep the quotes and to update the value.
If you are sure that the value will always be an integer and/or that you need an integer in your code you can do:
var numericValue = parseInt(val, 10);
Or if you are using lodash:
var numericValue = _.parseInt(val);
Remember to pass 10 as the second parameter which will specify the radix in the first case, as there may be edge cases in which numbers are interpreted with a base different than 10 (like hexadecimal or binary).
Otherwise if the value can be a float I suggest to do:
var numericValue = parseFloat(val);
And if you want to limit the digits after the decimal point you can do:
var numericValue = Number(parseFloat(val).toFixed(4));
.toFixed()
returns a string so if you still need a number it's better to convert it back to a number with the Number()
function.
Passing the value through an input may work but it doesn't look like a good practice, anyway to get the element you will need to add document
before getElementById
:
var val = document.getElementById('val').value;