Skywalker
Skywalker

Reputation: 5194

Javascript adding integers and decimals

I have a function where users can enter numbers like "5", "10", "0.47", "0.5" etc. And every time the user enters the data, the data is saved in an array.

I am using the following code to Add all the numbers in the array:

    $scope.uTotal = uMiles.reduce(addPrice, 0)

        function addPrice(a, b) {
            return a + b;
        }

The above code adds all the numbers successfully but if a user enters decimals values it does not add the decimals values.

For Example:

The values in the array currently are below, this was collected by doing console.log:

enter image description here

The output on the screen after running the above function is:

total = 5

but actually it should display total = 6.88

How can I make sure that no matter what number the user enters its added up and displayed on the front it exactly.

Upvotes: 2

Views: 2178

Answers (2)

Oriol
Oriol

Reputation: 288290

In your addPrice function, you use the operator + to sum the values.

But there is a problem: the values in the uMiles array are strings. Then, the addition operator + concatenates the strings instead of suming the numeric values.

To fix it, you must convert the strings to numbers.

  • Before reduce, using .map(Number):

    uMiles.map(Number).reduce(addPrice, 0);
    function addPrice(a, b) {
        return a + b;
    }
    
  • Inside addPrice, using the unary + operator:

    uMiles.reduce(addPrice, 0);
    function addPrice(a, b) {
        return a + +b;
    }
    

Upvotes: 1

BenM
BenM

Reputation: 53208

Use parseFloat() inside the function and you should be good:

function addPrice(a, b) 
{
    return a + parseFloat(b);
}

Upvotes: 5

Related Questions