Reputation: 5698
What is the regex for these cases:
29000.12345678900, expected result 29000.123456789
29000.000, expected result 29000
29000.00003400, expected result 29000.000034
In short, I want to eliminate the 0 point if there is no 1-9 found again behind decimal and I also want to eliminate the dot (.) if actually the number can be considered as integer.
I use this regex
(?:.0*$|0*$)
but it gives me this result:
29123.6 from 29123.6400, 4 is gone from there.
When I tested the regex separately, it works perfectly,
.0*$
gives me 29123 from 29123.0000
0*$
gives me 29123.6423 from 29123.642300
Am I missing something with the combined regex?
Upvotes: 3
Views: 125
Reputation: 9584
I don't know whether Objective-C supports something like the following construct, but in Python you can do it completely without regular expressions using str.rstrip()
:
In [1]: def shorten_number(number):
...: return number.rstrip('0').rstrip('.')
In [2]: shorten_number('29000.12345678900')
Out[2]: '29000.123456789'
In [3]: shorten_number('29000.000')
Out[3]: '29000'
Upvotes: 0
Reputation: 17194
You simply want this:
^\d*(\.?\d*[1-9])?
^\d*
that means one or more digit before the first group.()
that describes matching group.\.?
means single DOT(.)
can be there but optional. eg. (.)
\d*
there can be one or more digits. eg. (1234)
\.?\d*
there can be one DOT and one or more digit eg. (.123)
[1-9]
this includes only digit from 1 to 9 only excluding 0
. eg. (2344)
Upvotes: 0
Reputation: 32807
You can use this regex
^\d+(\.\d*[1-9])?
- -------------
| |->this would match only if the digits after . end with [1-9]
|
|->^ depicts the start of the string..it is necessary to match the pattern
that solves your problem
try it here
Upvotes: 3
Reputation: 298246
If you think regex is the best way of doing it, you can just use something like this:
\.?0+$
It works for both cases:
> '12300000.000001130000000'.replace(/\.?0+$/g, '')
"12300000.00000113"
> '12300000.000000000000'.replace(/\.?0+$/g, '')
"12300000"
Upvotes: 3