Skip to content
Advertisement

How to add float together as actual numerical values in Javascript

I am working on an app and part of it requires adding values together.

I have a form where a user can enter a dollar amount which allows floats i.e. 55.25 etc… When a a new item is submitted via the form, the totals get added together. Using whole numbers is easy but I want float numbers to be added together on each form submission. The struggle is that to get numbers to display I use parseFloat().toFixed(2) but adding strings together just gives a string value not a mathematical/decimal value.

How can I achieve this?

totalAmount(() => {
        let totalPayment = '0.00';

        if (items.length > 0) {
          for (let i = 0; i < items.length; i++) {
            let item = JSON.parse(JSON.stringify(items[i]));

            totalPayment = parseFloat(totalPayment) + parseFloat(item.amount).toFixed(2);
          }
        }

        return totalPayment;
      }),

Input field

<input type="number" required min="0" id="amount" step=0.01>

Advertisement

Answer

You can put a + sign before each item to transform it to numerical and then .toFixed the result

totalPayment = (+totalPayment + +item.amount).toFixed(2)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement