Page 1 of 1

remove trailing zeros only if a floating point number

Posted: Tue Aug 29, 2006 5:33 pm
by buldir
I am not new to regex, but this one boggles my mind. I would like to match any number of trailing zeros and the decimal point only if the string is a floating point number and only zeros exist to the right of decimal point, else match the trailing zeros of the floating point number. If the number is not a floating point number, then do nothing.

Matches: 100.0 | 100.00 | 100.05000

Does not match: 100 | 100.05 | 123

What I have so far is:

Code: Select all

(?(\d+\.(0+))\.0+$|0+$)
Any help would be greatly appreciated.

Posted: Tue Aug 29, 2006 6:00 pm
by feyd

Code: Select all

$number = rtrim($number, '0.');

Posted: Tue Aug 29, 2006 6:15 pm
by buldir
Thanks for the reply, feyd. I am not using php, but VB .NET to replace the trailing zeros with nothing, so all I need is the regex string:

Code: Select all

Friend Function SplitPosAcc(ByVal input As String) As String
        Dim re As New Regex("regex_string")
        Return re.Replace(input, "").Trim
    End Function

sNumVal = numPosAcc.Value.ToString 'get the accuracy value in raw form
sNumVal = (SplitPosAcc(sNumVal))
Using VB .NET code such as:

Code: Select all

sNumVal = sNumVal.TrimEnd("0"c)
will unfortunately chop off the zeros in the number 100.

Posted: Tue Aug 29, 2006 6:29 pm
by feyd
buldir wrote:Thanks for the reply, feyd. I am not using php, but VB .NET to replace the trailing zeros with nothing
It would have been nice to know that before... :P

I don't know what kind of regex vb.net uses, so ...

Code: Select all

#^(?:(\d+)(?:\.0*)?|(\d+\.\d+?)0*)$#
Use of that pattern in PHP.

Code: Select all

[feyd@home]>php -r "$a = array('100', '100.00', '105.', '105', '150', '150.00060'); foreach($a as $s){ preg_match('#^(?:(\d+)(?:\.0*)?|(\d+\.\d+?)0*)$#', $s, $match); var_dump($match); }"
array(2) {
  [0]=>
  string(3) "100"
  [1]=>
  string(3) "100"
}
array(2) {
  [0]=>
  string(6) "100.00"
  [1]=>
  string(3) "100"
}
array(2) {
  [0]=>
  string(4) "105."
  [1]=>
  string(3) "105"
}
array(2) {
  [0]=>
  string(3) "105"
  [1]=>
  string(3) "105"
}
array(2) {
  [0]=>
  string(3) "150"
  [1]=>
  string(3) "150"
}
array(3) {
  [0]=>
  string(9) "150.00060"
  [1]=>
  string(0) ""
  [2]=>
  string(8) "150.0006"
}

Posted: Tue Aug 29, 2006 6:52 pm
by buldir
My bad, feyd. php is quite nice. Unfortunately, I don't know what kind of regex VB .NET uses. I will continue to plod on.

Posted: Tue Aug 29, 2006 7:31 pm
by buldir
I think I got it:

Code: Select all

(?<=\d+\.\d+)0+$|\.0+$