### Archive

Posts Tagged ‘Numbers’

## HowTo: Extract numeric suffix from a string in Python

I recently needed to extract a numeric suffix from a string value in Python. Initially I did the following:

import re

def extractNumSuffix(value):

return (None if (search:=re.search(‘^\D*(\d+)\$’, value, re.IGNORECASE)) is None else search.group(1))

Note that return has a single-line expression.

So

print(extractNumSuffix("test1030"))

prints 1030

Tried it online at:

https://repl.it/languages/python3

However, then I found out that Assignment Expressions in Python only work from Python 3.8 and up, so I changed it to this one:

import re

def extractNumSuffix(value):
search=re.search(r"^\D*(\d+)\$", value, re.IGNORECASE)
return (None if search is None else search.group(1))

which should work in Python 2.x too. Don’t forget to import the regular expressions (re) module.

Categories: Posts

## HowTo: round a number up to N decimal digits in Javascript

Was just trying to round-off some Google Maps coordinates for display in Javascript up to 3 decimal digits and that was a bit like a blast from the past (the end of the ‘90s to be more accurate)…

So here’s my contributed answer at:
https://stackoverflow.com/questions/2221167/javascript-formatting-a-rounded-number-to-n-decimals

This works for rounding to N digits (if you just want to truncate to N digits remove the Math.round call and use the Math.trunc one):

function roundN(value, digits) {
var tenToN = 10 ** digits;
return /*Math.trunc*/(Math.round(value * tenToN)) / tenToN;
}

Had to resort to such logic at Java in the past when I was authoring data manipulation E-Slate components. That is since I had found out that adding 0.1 many times to 0 you’d end up with some unexpectedly long decimal part (this is due to floating point arithmetics).

A user comment at Format number to always show 2 decimal places calls this technique scaling.

Some mention there are cases that don’t round as expected and at http://www.jacklmoore.com/notes/rounding-in-javascript/ this is suggested instead:

function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}

Categories: Posts