0

I'm trying to truncate some longitude coordinates without any rounding issues. I thought replace() would be the simplest way to do this.

My regex is correct, but I'm apparently not using replace correctly.

Here's my stripped down example. I need to strip all decimal points after the 8th position

var truncRegex = /-?\d+?\.\d{8}/;
console.log('-81.82297519999997'.replace(truncRegex, '$1'));

What's happening is replace() is stripping the match and leaving me with the remainder prepended with "$1". The result is: $1999997

1
  • 1
    If you aren't concerned about rounding, you could use Number("...").toFixed(8) Commented Dec 11, 2014 at 23:39

4 Answers 4

1

You've got some answers of RegExp. Alternatively, you could just find the index of the point and retrieve a substring, if you don't care about rounding.

var str = '-81.82297519999997';
var truncated = str.substring(0, str.indexOf('.') + 9); // this will give you 8 fractions
console.log(truncated); // "-81.82297519"
Sign up to request clarification or add additional context in comments.

1 Comment

This was my fix. Thank you.
0

You must add matching groups in parentheses to match something that you can refer to with $1 while replacing. For example:

var truncRegex = /(-?\d+?\.\d{8})\d*/;
console.log('-81.82297519999997'.replace(truncRegex, '$1'));

replace() function replaces everything it matches based on regular expression. Your code simply replaces -DD.DDDDDDDD with '$1' string.

You can still use expression you provided, but you will have to use match, not replace, e.g.:

var truncRegex = /-?\d+?\.\d{8}/;
console.log('-81.82297519999997'.match(truncRegex)[0]);

Comments

0
var s = '81.82297519999997';

// Returns "-81.82297519"
s.replace(/(-?\d+\.\d{8})\d*/, '$1');

Comments

0
(-?\d+?\.\d{8})|.*

Try this.Replace by $1.See demo.

https://regex101.com/r/eZ0yP4/17

var re = /(-?\d+?\.\d{8})|.*/mg;
var str = '-81.82297519999997';
var subst = '$1';

var result = str.replace(re, subst);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.