'Remove leading zeros in powershell
I have several strings and try to remove the leading zeros for them. I know I can use TrimStart() but it's wrong if all numbers are zero.
$Test = "00000.22"
$Test = $Test.trimstart('0')
The result is .22 and what I expect is 0.22. How can I achieve it? Thank you.
Solution 1:[1]
A purely textual solution is to use the -replace operator with a regular expression:
PS> '00000.22' -replace '^0+', '0'
0.22
^0+ matches one or more (+) zeros at the start (^) of the string and replaces them with a single zero.
If you also want to make sure that numbers with an integral part that isn't 0 and/or without a fractional part are properly handled, use
-replace '^0+(?=[^.])' (note the absence of a substitution operand, which effectively removes what gets matched):
PS> ('00000.22', '0000', '00001.22').ForEach({ $_ -replace '^0+(?=[^.])' })
0.22
0
1.22
Positive look-ahead assertion (?=[^.]) effectively removes all leading zeros (^0+) as long as such a zero isn't followed by a literal . ([^.]).
If you do want something like '00000.22' to become just '.22', i.e. if you want to drop the integral part if it happens to be 0, the regex becomes simpler: '^0+(?=.)'
gms0ulman's answer is convenient and probably works fine in most cases, but there are pitfalls:
You're changing the data type to
[decimal], and converting that back to a string can result in a culture-specific representation where.is converted to,(that said, PowerShell itself often applies the invariant culture, which always uses.); e.g.:# Cast to [decimal] using the German culture ('de') PS> [System.Threading.Thread]::CurrentThread.CurrentCulture = 'de'; [decimal] '0000.22' 0,22 # !! Note the "," instead of "."Even though unlikely with a high-precision data type such as
[decimal], rounding errors are possible:PS> [decimal] '00.99999999999999999999999999999' 1.0000000000000000000000000000 # !! rounding occurred
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
