格式化百分比小数位并删除尾随零

Format percentage decimal places and remove trailing zeros

考虑以下代码:

$Obj = @(
    [PSCustomObject]@{
        LimitNew        = 5368709120
        Usage           = 6166915072
    }
    [PSCustomObject]@{
        LimitNew        = 10737418240
        Usage           = 5368709120
    }
    [PSCustomObject]@{
        LimitNew        = 107374182400
        Usage           = 86973087744
    }
    [PSCustomObject]@{
        LimitNew        = 107374182400
        Usage           = 97710505984
    }
)

$CultInfo = New-Object System.Globalization.CultureInfo -ArgumentList 'en-us',$false
$CultInfo.NumberFormat.PercentDecimalDigits = 2
$Obj |select @{L='pct used';E={($_.Usage/$_.LimitNew).ToString('P', $CultInfo)}}

它returns输出如下:

pct used
--------
114.87 %
50.00 % 
81.00 % 
91.00 % 

我真正想要的是以下输出:

pct used
--------
114.87 %
50 % 
81 % 
91 % 

阅读 documentation 时,我似乎无法找到省略尾随零的选项。方法 $CultInfo.NumberFormat.PercentDecimalDigits 指定查看小数点后的位数,但不指定如何省略零。

同时阅读Custom Numeric Format Strings

The "%" Custom Specifier

A percent sign (%) in a format string causes a number to be multiplied by 100 before it is formatted. The localized percent symbol is inserted in the number at the location where the % appears in the format string. The percent character used is defined by the PercentSymbol property of the current NumberFormatInfo object.

下面的代码片段应该可以解决问题:

$Obj | Select-Object @{
    L='pct used';
    E={($_.Usage/$_.LimitNew).ToString('#0.## %', $CultInfo)}
    }

结果:

pct used
--------
114.87 %
50 %    
81 %    
91 %