Extract a Number from a String with JavaScript

User input from HTML form fields is generally provided to JavaScript as a string. We’ve lived with that fact for decades but sometimes developers need to extract numbers from that string. There are multiple ways to get those numbers but let’s rely on regular expressions to extract those numbers! To employ a regular expression to get a number within a string, we can use \d+: const string = "x12345david"; const [match] = string.match(/(\d+)/); match; // 12345 Regular expressions are capable of really powerful operations within JavaScript; this practice is one of the easier operations. Converting the number using a Number() wrapper will give you the number as a Number type. The... more →
Posted in: JavaScript

Followup to My Intl Short Number Post

A few days ago I shared a blog post about using the Intl object in JavaScript to create short, more readable numbers. So for example, instead of 9123456, it would display 9.1M. This was done using the notation option in Intl.NumberFormat. Yesterday I randomly ran into an interesting modification on this using yet another option, compactDisplay. The compactDisplay option is only used when notation is set to compact. It supports two options, short which is default and what I demonstrated in the previous post, and long. So given a number, i, you would use it like so: new Intl.NumberFormat('en-US', { notation:'compact', compactDisplay:'long'}).format(i); And the result is, well, longer. 😉 What’s... more →
Posted in: JavaScript

Short Number Formatting in Python

Yesterday I wrote a blog post about creating short number formats in JavaScript. Definitely check out that post first, but the idea was to take something like 9496301 and display it as 9.5M. In that post, I used the built-in Intl object and it worked really well. It got me thinking, could you do the same in Python? First off, I checked and was happy to see that like JavaScript, Python supports numeric separators. This makes it much easier to read large numbers in code. It also meant I could take my test array and copy and paste it into a Python program: inputs = [ 999, 1000, 2999, 12_499, 12_500, 430912, 9_123_456, 1_111_111_111, 81_343_902_530, 1_111_111_111_111, 62_123_456_789_011,... more →
Posted in: JavaScript

V8 Javascript Fixes (Horrible!) Random Number Generator – Hackaday

Hackaday V8 Javascript Fixes (Horrible!) Random Number GeneratorHackadayTo quantify the above observations, the official V8 Javascript post that I linked above notes that the coverage is only 232 values out of the possible 252 uniformly-distributed values that a 64-bit float can represent. This is a huge failure of the …and more » JavaScript – Google News… more →
Posted in: JavaScript