Skip to content

Instantly share code, notes, and snippets.

@dela3499
Created August 26, 2016 02:16
Show Gist options
  • Save dela3499/5f5fbc615735436fcee8c48a7c44ddb6 to your computer and use it in GitHub Desktop.
Save dela3499/5f5fbc615735436fcee8c48a7c44ddb6 to your computer and use it in GitHub Desktop.
How to convert strings to integers in JavaScript, and sum the values in an array
// Convert string to number
string = '12.1';
number = parseFloat(string);
// Convert float to int
myInt = Math.floor(number);
// Convert list of strings to list of ints
strings = ['1.1','2.1','3.1'];
numbers = strings.map(parseFloat);
ints = numbers.map(Math.floor);
// Sum the list of integers
add = function (a, b) { return a + b; };
intSum1 = ints.reduce(add, 0);
// Sum list of integers in a general way
sum = function (xs) {
return xs.reduce(add, 0);
}
intSum2 = sum(ints);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment