I am currently available for freelance/contract work. Book a meeting so we can talk about your project.

Extracting floats from strings

Posted on

To get all float values from a sentence, we can first find them with a regular expression and then map over the matches with parseFloat.

// matches all integer or decimal substrings, like “69” or “4.20”
const numbersRegexp = new RegExp(/\d+(\.\d+)?/, "g")
 
// finds all numbers matching the expression and transforms them to numbers
const getFloatsFrom = (string) => string.match(numbersRegexp).map(parseFloat)
 
getFloatsFrom("Put the 16 cupcakes in the oven (at 180°C) for 1.5 hours.")
// ⇒ [16, 180, 1.5]
// matches all integer or decimal substrings, like “69” or “4.20”
const numbersRegexp = new RegExp(/\d+(\.\d+)?/, "g")
 
// finds all numbers matching the expression and transforms them to numbers
const getFloatsFrom = (string) => string.match(numbersRegexp).map(parseFloat)
 
getFloatsFrom("Put the 16 cupcakes in the oven (at 180°C) for 1.5 hours.")
// ⇒ [16, 180, 1.5]
Debug
none
Grid overlay