gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:41:18 26 4
gpt4 key购买 nike

考虑以下代码:

$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)}}

它返回以下输出:

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 %

关于powershell - 格式化百分比小数位并删除尾随零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50036281/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com