2

I need to remove training Zero's on a number like: 9.2500 = 9.25 Thanks to a previous post by @Avinash Raj I found this:

^(\d+\.\d*?[1-9])0+$

Which works perfect for that application. However, in some cases I have a number like 11.0000 and the above RegEx returns:

11.0

I need to return:

11

I'm not sure how to remove the decimal and zero when there is not one needed? I've spend some time trying to figure it out but I'm stumped.

BobTucker
  • 35
  • 1
  • 4
  • The fact that you *can* do it with regex doesn't mean that you *should* ;) which programming language are you using ? – Nir Alfasi Oct 13 '17 at 21:59
  • @alfasin I am using an automation application. My only option to clean is regex. If could use java I'd be done. – BobTucker Oct 13 '17 at 22:03
  • Bob, you're asking for one regex that will do two different tasks (can you see why?). Another idea: run it once, and then run another regex to update numbers in the format: `n.0` to `n` – Nir Alfasi Oct 13 '17 at 22:10
  • @BobTucker Try a [regex](https://regex101.com/r/T4qmV5/1) from [my old answer](https://stackoverflow.com/a/35351336/3832970). It might suffice, or it may do more than you need. Just select the alternatives you need. – Wiktor Stribiżew Oct 13 '17 at 22:12

3 Answers3

5
^(\d+(?:\.\d*?[1-9](?=0|\b))?)\.?0*$

Demo here.


explanation

^         //Beginning of line
(         //Start collecting our group
\d+       //All digits before decimal
(?:       //START-Non collecting group
\.        //Decimal point
\d*?      //It should actually be [0-9]
[1-9]     //Last significant digit after decimal
(?=0|\b)  //Either should be followed by zero or END OF WORD
)?        //END-Non collecting group
          //The non-capturing group after decimal is optional
)         //End collecting our group
\.?       //Optional decimal (decimal collected if it wasn't used earlier)
0*        //All the remaining zeros no + as all digits might be significant that is no ending zero
$         //End of line.
kaza
  • 2,317
  • 1
  • 16
  • 25
3

Try this one:

^(\d*[\d.]*?)\.?0*$

Regex101 here.

Psidom
  • 209,562
  • 33
  • 339
  • 356
1

Try this one

^\d*\.[1-9]*([0]+)*$

Explanation

^  beginning of the term
\d*  digits from 0-9 those can be any number (can be 0 number or more)
\.   escaping the .
[1-9]* numbers from 1 to 9 (can be 0 number or more)
([0]+)  capturing all 0s in group1
$  end of the term

Regex101 here

JBone
  • 1,724
  • 3
  • 20
  • 32