I was looking for a way to trim floats to a certain number of decimal places without rounding. After some googling, I found this:
15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/)
This works great, returning 15.77. I'm building an application which will include different floats which need to be trimmed to a given number of places, so I'm trying to convert this into a function that I can give my float, and the number of decimal places I want, and get the result.
I've come up with this:
function floatTrim(num) {
var dec = '2',
exFrame = '^\d+(?:\.\d{0,' + dec + '})?',
ex = new RegExp(exFrame),
j = num.toString(),
out = j.match(ex);
console.log(out);
}
... where the 'dec' variable equals the number of decimal places to trim to. However, when I run this function with the float 15.7784514000 from above, it returns null, and I can't figure out why. Can anyone offer some insight?