Welcome to the Onshape forum! Ask questions and join in the discussions about everything Onshape.

First time visiting? Here are some places to start:

  1. Looking for a certain topic? Check out the categories filter or use Search (upper right).
  2. Need support? Ask a question to our Community Support category.
  3. Please submit support tickets for bugs but you can request improvements in the Product Feedback category.
  4. Be respectful, on topic and if you see a problem, Flag it.

If you would like to contact our Community Manager personally, feel free to send a private message or an email.

Limiting decimal precision in print() with Regex

RootentityRootentity Member Posts: 19 ✭✭
I am working on making a simple CAM drilling feature script.  
https://cad.onshape.com/documents/b571df08ddf1c4635358bf69/w/110a6ada5e5acec1cbc03228/e/fc6f2559c19db616bda0b63c

I need to limit decimal precision because many controllers, and some G code senders choke on long numbers.
I started by multiplying rounding and then dividing to trim the decimal places, but that didn't guarantee only four decimal places in every case. so now I am converting to strings and using a regular expression to trim the trailing digits off, however my expression is failing in some cases and I don't know why.

Here is the expression in question:
(-?\\d*\\.\\d{1,4}|^\\d$)

and Broken down:

-? = optional minus sign
d* = any number of digits
.d{1,4} = a decimal place followed by one to four digits
| ^d$ = or if it's not the previous format it's just a single digit

It's failing on numbers like 0.4 with a single digit a decimal and a single digit.  I am certainly no master at Regex, I can't figure out why it isn't caught by the first case?

Maybe I'm all off course and there is a simpler way to do this?

Best Answer

  • RootentityRootentity Posts: 19 ✭✭
    Accepted Answer
    I've solved this problem, I was using REGEX_NUMBER_CAPTURE to capture everything left over and this was causing the trouble. I've replaced the expression with this "([\\d-]+\\.\\d{1,4})\\d*?"  The \\d*? at the end accounts for all of the remaining digits after the needed four digits.

Answers

  • RootentityRootentity Member Posts: 19 ✭✭
    Just did a bit more testing.  It is capturing one less digit than it should be up until there are five digits behind the decimal place.  If the number is 1.2 it fails, 1.23 captures 1.2, 1.234 captures 1.23, 1.23456 captures 1.2345, and 1.2345678910 captures 1.2345 as well.
  • RootentityRootentity Member Posts: 19 ✭✭
    Accepted Answer
    I've solved this problem, I was using REGEX_NUMBER_CAPTURE to capture everything left over and this was causing the trouble. I've replaced the expression with this "([\\d-]+\\.\\d{1,4})\\d*?"  The \\d*? at the end accounts for all of the remaining digits after the needed four digits.
Sign In or Register to comment.