2

How can I to sum elements of a JSON array like this, using jQuery:

{"formulagram":"470+6,7+33,5+236,2+4,5+0,3"}

and the result should be :

total : 751,2

Nominal with comma and + is a sparator.

Thank you

  • 2
    What does the comma in `751,2` separate? You need to elaborate more on what is being summed. – Austin Brunkhorst Jan 13 '16 at 03:18
  • @AustinBrunkhorst : total shown are not always round. but also coma and + serves merely as a separator nominal figures such as coma if nominal not with commas. – riski maker Jan 13 '16 at 03:25

3 Answers3

1

TRY THIS:

var objForm = {
    formulagram:"470+6,7+33,5+236,2+4,5+0,3"
};

var str= objForm.formulagram;

str = str.split(',').join('.').split('+');

var total = 0;
$.each(str,function() {
    total += parseFloat(this);
});

total = Math.round(total * 100) / 100;

total = total.toString().replace('.',',');

console.log(total);

I have created a demo below:

var objForm = {
  formulagram: "470+6,7+33,5+236,2+4,5+0,3"
};

var str = objForm.formulagram;

str = str.split(',').join('.');

$('#splitbyComma').html(str);

str = str.split('+');

var total = 0;
$.each(str, function() {
  total += parseFloat(this);
});

total = Math.round(total * 100) / 100;

total = total.toString().replace('.',',');

$('#result').html(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p>Replace Comma with dot (.)</p>
<p id="splitbyComma"></p>
<p><strong>Total:</strong>
</p>
<p id="result"></p>
vsogrimen
  • 456
  • 2
  • 7
0

You have to replace the character ',' for '.' to represent floating numbers. Then you can use eval.

Code:

var str= "470+6.7+33.5+236.2+4.5+0.3";
var sum = parseFloat(eval(str));

You have to be careful because it can be risky to use eval. Read more in this thread Why is using the JavaScript eval function a bad idea?

Community
  • 1
  • 1
iamdeit
  • 5,485
  • 4
  • 26
  • 40
0

Here's a more roundabout but automated way:

var formulaObject = JSON.parse({"formulagram":"470+6,7+33,5+236,2+4,5+0,3"})
var formulaString = formulaObject.formulagram
var formulaPoint = formulaString.replace(',', '.')
var formulaArray = formulaPoint.split('+')
var formulaSum = formulaArray.reduce(function(prev, cur) {
    return prev + parseFloat(cur)
}, 0)
Jason Kennaly
  • 622
  • 1
  • 5
  • 9