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
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
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>
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?
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)