Reputation: 97
I need to create a String from double the use String.Trim() to remove the full stop, but it doesn't remove it. I think there is also a way to do this numerically but I'd like to do it with the string. Is there a reason it won't remove it? The output from the code is 5.5
$MyDouble = 5.5
[String]$MyDouble2 = $MyDouble
$MyDouble2.Trim(".")
$MyDouble2
Upvotes: 1
Views: 6028
Reputation: 438093
String.Trim()
only trims from the beginning and end of strings, so it has no effect in your command, because the .
only occurs inside your input string.
If you truly want to remove just the .
and keep the post-decimal-point digits, use the -replace
operator:
$MyDouble2 -replace '\.' # -> '55'
Note:
* -replace
takes a regex (regular expression) as the search operand, hence the need to escape regex metacharacter .
as \.
* The above is short for $MyDouble2 -replace '\.', ''
. Since the replacement string is the empty string in this case, it can be omitted.
If you only want to extract the integer portion, use either 4c74356b41's .Split()
-based answer, or adapt the regex passed to -replace
to match everything from the .
through the end of the string.
$MyDouble2 -replace '\..*' # -> '5'
@Matt mentions the following alternatives:
For removing the .
only: Using String.Replace()
to perform literal substring replacement (note how .
therefore does not need \
-escaping, as it did with -replace
, and that specifying the replacement string is mandatory):
$MyDouble2.Replace('.', '') # -> '55'
For removing the fractional part of the number (extracting the integer part only), using a numerical operation directly on $MyDouble
(as opposed to via the string representation stored in $MyDouble2
), via Math.Floor()
:
[math]::Floor($MyDouble) # -> 5 (still a [double])
Upvotes: 4
Reputation: 46710
Looking at some documentation for .Trim([char[]])
you will see that
Removes all leading and trailing occurrences of a set of characters specified in an array from the current String object.
That does not cover the middle of strings, so using the .Replace()
method would accomplish that.
I think there is also a way to do this numerically but I'd like to do it with the string.
Just wanted to mention that converting numbers to strings to then drop decimals via string manipulation is a poor approach. Assuming your example is what you are actually trying to do, I suggest using a static method from the [math]
class instead.
$MyDouble = 5.5
[math]::Floor($MyDouble)
Upvotes: 3
Reputation: 17472
$MyDouble = 5.5
[String]$MyDouble2 = $MyDouble
$res=$MyDouble2 -split "\."
$res[0..($res.Count-1)] -join ""
Upvotes: 0
Reputation: 17472
$MyDouble = 5.5
[String]$MyDouble2 = $MyDouble
$MyDouble2.Replace(".", "")
Upvotes: 1
Reputation: 72171
Well, why would it trim not the last (or first) character? It wouldn't, what you need (probably) is:
$MyDouble = 5.5
[String]$MyDouble2 = $MyDouble
$MyDouble2.Split(".")[0]
Upvotes: 0