hyprstack hyprstack - 8 months ago 50
Javascript Question

JavaScript: Retrieve negative floating point number from string of mutiple sums

I have a simple app that allows me to caculate the total amount invoiced and deposited in a route. However I want to allow the user to input multiple values in a single input field; e.g:


I have written a function that will retrieve this input and then
this string into elements of an array at the
sign and immediately parse the values to numbers and then add them and return the total the user inputs into each individual field. This is all well as long as the user does no use any sign other than

I have searched the use of

but none of the results seem to work.
How could I make my code retrieve the values so that the negative values get passed into the array as negative values?

Here is a snippet of my Js code:
For the full code, visit my fiddle.

totalInvoiced: function () {

var a = A.invoiced.value;
var value1Arr = [];
value1Arr = a.split("+").map(parseFloat);
var value1 = 0;
value1Arr.forEach(function (value) {
value1 += value;

Answer Source

I really like PhistucK's solution, but here an alternative with regex:

value1Arr = a.split(/(?=\+|\-)/);

This will split it, but keeps the delimiter, so the result will be:

["500", "+50", "+36.5", "-45.2", "-10"]