Home > front end >  RegEx vscode - replace decimal places and round correctly
RegEx vscode - replace decimal places and round correctly

Time:07-14

Is it possible to use regex to round decimal places?

I have lines that look like this but without any spaces (space added for readability).

0,      162.3707542,   -162.3707542
128.2,  151.8299471,   -23.62994709 // this 151.829 should lead to 151.83

I want to remove all numbers after the second decimal position and if possible round the second decimal position based on the third position.

0,      162.37,   -162.37
128.2,  151.82,   -23.62     // already working .82
...,    151.83,   ...     // intended .83 <- this is my question

What is working

The following regex (RegEx mapped groups

In Visual Studio Code Search and replace with RegEx

This Replacement / Substitution

Question

Is it possible to change the last digit of $2 (group two) based on the first digit in $3 (group three) ?

My intention is to round correctly. In the sample above this would mean

151.8299471 // source
151.82      // current result
151.83      // desired result 2 was changed to 3 because of third digit 9 

CodePudding user response:

It was easier than I thought, once I found the Number.toFixed(2) method.

Using this extension I wrote, round to 2 decimal digits demo with regex find


If you do want to truncate things like 4.00 to 4 or 4.20 to 4.2 use this replace instead.

"replace": [
  "$${",
            
    "let result = $1.toFixed(2);",
    "result = String(result).replace(/0 $/m, '').replace(/\\.$/m, '');",
    "return result;",
      
  "}$$"
],

CodePudding user response:

It is not only that you need to update the digit of $2. if the number is 199.995 you have to modify all digits of your result.

You can use the extension Regex Text Generator.

You can use a predefined set of regex's.

  "regexTextGen.predefined": {
    "round numbers": {
      "originalTextRegex": "(-?\\d \\.\\d )",
      "generatorRegex": "{{=N[1]:fixed(2):simplify}}"
    }
  }

With the same regex (-?\\d \\.\\d ) in the VSC Find dialog select all number you want, you can use Find in Selection and Alt Enter.

Then execute the command: Generate text based on Regular Expression.

Select the predefined option and press Enter a few times. You get a preview of the result, you can escape the UI and get back the original text.

In the process you can edit generatorRegex to change the number of decimals or to remove the simplify.

  • Related