Round all the numbers in an array, and display the sum: - Javascript Math

Javascript examples for Math:round

Description

Round all the numbers in an array, and display the sum:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<body>

<button onclick="myFunction()">Test</button>

<p>Sum of numbers in array: <span id="demo"></span></p>

<script>
var numbers = [15.5, 2.3, 1.1, 4.7];

function getSum(total, num) {// w ww  . j a  v  a2  s.  c o  m
    return total + Math.round(num);
}
function myFunction(item) {
    document.getElementById("demo").innerHTML = numbers.reduce(getSum, 0);
}
</script>

</body>
</html>

Related Tutorials