且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Powershell:将字符串转换为数字

更新时间:2021-12-04 23:16:02

简单地将字符串转换为 int 不会可靠地工作.您需要将其转换为 int32.为此,您可以使用 .NET convert 类及其 ToInt32 方法.该方法需要一个 string ($strNum) 作为主要输入,以及 base number (10) 作为主要输入要转换到的数字系统.这是因为您不仅可以转换为十进制系统(10 基数),还可以转换为例如二进制系统(基数 2).

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).

试试这个方法:

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

$intNum