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
  • 2
    What does the comma in 751,2 separate? You need to elaborate more on what is being summed. Commented Jan 13, 2016 at 3: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. Commented Jan 13, 2016 at 3:25

3 Answers 3

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>

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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?

1 Comment

Obligatory comment about security implications of eval.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.