powershell - Powershell添加不需要的小数(加法)

标签 powershell powershell-5.0

我正在其中一个脚本中做一些附加操作,下面是一些简化的代码:

foreach($entry in $arr){
...
switch($entry.AccessRights)
{

"GenericRead" {$score = 1}
"GenericWrite" {$score = 2}
"GenericAll" {$score = 3}
default {$score = 0.1}
}
$users | where {$_.username -eq $entry.username} | % {$_.aclscore+=$score}
}

您期望输出为123.5之类的值。但是在两者之间的某个时间点(分数为0.1时),它会偏离0.0000000000001正负,所以我可能会得到类似66,1000000000001甚至84,8999999999999的结果。

问题1:为什么?

问题2:除了事后取整外,我还能做些什么来解决?

最佳答案

在测试时,PowerShell隐式将变量的数据类型强制转换为[double]。而是显式转换为[decimal]

  • Double数据类型可以容纳很大范围的值,但是会牺牲精确度。
  • 十进制使用更多的内存(12个字节,而 double 8个字节),值的范围更短,但保留精度。

  • 这绝不是深入的比较。我建议您阅读this table of datatypes并在线查找更完整的解释,因为这是非常基础的并且与语言无关。

    代码
    foreach($entry in $arr){
        ...
        switch($entry.AccessRights)
        {
    
            "GenericRead" {[decimal]$score = 1}
            "GenericWrite" {[decimal]$score = 2}
            "GenericAll" {[decimal]$score = 3}
            default {[decimal]$score = 0.1}
    
        }
    
        $users | where {$_.username -eq $entry.username} | % {$_.aclscore+=$score}
    
    }
    

    编辑-进一步的说明

    由于数字存储在binary中,并且某些数字无法精确地用二进制表示,因此double数据类型缺乏精度。

    沃尔特·米蒂(Walter Mitty)的评论提供了一个1/3的很好的例子,这个数字无法使用有限数量的十进制或二进制数字精确表示:
    1/3 = 0.333333333..... [decimal]
    1/3 = 0.010101010..... [binary]
    

    同样,分数1/10 cannot be expressed exactly in binary。而可以十进制表示。
    1/10 = 0.1             [decimal]
    1/10 = 0.000110011.... [binary]
    

    关于powershell - Powershell添加不需要的小数(加法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45674415/

    相关文章:

    powershell - 为什么 PowerShell 5 中的最大变量计数为 4096

    string - Powershell - 从 PsObject 中的 AD 属性获取最后 3 个字符

    .net - 如何判断 new-object 来自哪个版本的程序集?

    class - Powershell 5 类,构造函数或方法中的写入调试或写入详细输出

    windows - 在Windows 7中获取本地端口号

    powershell - 如何向现有 PowerShell 对象添加成员?

    windows - 在 Windows 的 Powershell 中使前台成为由 Start-Job 调用的后台作业

    powershell - 只能使用交互式输入的凭据建立远程Powershell session 吗?

    powershell - 将字符串转换为int并仅对TFS中的内部版本号递增最后一位

    arrays - 对两个数组使用类运算符