Is this right way to convert data attributes values to number in javascipt? Need to get valid numeric value or 0

I am using the following code to convert data attribute values to Numbers. I want to get a valid numeric value or 0 in all cases. e.g if the data attribute value is blank(“”) then I need 0 in that case.

I am using the following code to convert data attribute values to Numbers. I want to get a valid numeric value or 0 in all cases. e.g if the data attribute value is blank(“”) then I need 0 in that case. The intention is to avoid getting NaN because I am using the result in calculations.

Number($("td[id^='tdCumulativeUnderOverSpendPrevious']").data("val") || 0);

Is this right way to convert data attributes values to number in javascipt?

If the data attribute is called val then yeah, that’ll do the trick.

Nowadays however, I tend towards making things more verbose, so that future me doesn’t have to spend as much brain power reading code I wrote previously:

const $tdElement = $("td[id^='tdCumulativeUnderOverSpendPrevious']");
const tdValue = Number($tdElement.data('val')) || 0;
console.log(tdValue);

And although I still use jQuery, I have started to replace it in favor of vanilla JS where possible. In this case it takes little effort

const tdElement = document.querySelector("td[id^='tdCumulativeUnderOverSpendPrevious']");
const tdValue = Number(tdElement.dataset.val) || 0;
console.log(tdValue);

HTH

2 Likes

14 posts were split to a new topic: The advantage of using Number() instead of parseInt or parseFloat

Thanks a lot. Appreciated.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.