Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

Powershell: convert string to number

Ok, I am beginner - and lost with this:

I have an Array where some drive data from WMI are captured:

$drivedata = $Drives | select  @{Name="Kapazit?t(GB)";Expression={$_.Kapazit?t}}

The Array has these values (2 drives):

@{Kapazit?t(GB)=1.500} @{Kapazit?t(GB)=1.500}

and just want to convert the 1.500 into a number 1500

I tried different suggestions I found here, but couldn't get it working:

-Replace ".","" and [int] doesn't work. I am not sure if regex would be correct and how to do this.

For help many thanks in advance.

question from:https://stackoverflow.com/questions/25322636/powershell-convert-string-to-number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Simply casting the string as an int won't work reliably. You need to convert it to an int32. For this you can use the .NET convert class and its ToInt32 method. The method requires a string ($strNum) as the main input, and the base number (10) for the number system to convert to. This is because you can not only convert to the decimal system (the 10 base number), but also to, for example, the binary system (base 2).

Give this method a try:

[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)

$intNum

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...