【问题标题】:Round all numbers in CSV to two decimal points将 CSV 中的所有数字四舍五入到小数点后两位
【发布时间】:2015-07-01 18:29:18
【问题描述】:

我想对 CSV 文件中小数点后第二位的所有数字进行四舍五入(或简单地删除)。

我知道[Math]::Round() 和.NET 版本的'{0:f2}'。只是不知道如何将其应用于整个 CSV 文件。

【问题讨论】:

  • 将 CSV 文件导入 powershell,并使用您提到的 [system.math]::round 处理每个项目,然后导出到新的 csv 文件

标签: powershell csv scripting rounding


【解决方案1】:

假设您有这样的 csv 文件:

Name  Num1       Num2       Num3     
----  ----       ----       ----     
Test1 4.2414     346.2425   33.24124 
Test2 123.35235  56.35235   326.23535
Test3 12424.2424 57.3525    466.3525 
Test4 4364.343   12.241212  1.12424  
Test5 12.552353  464.352353 346.4646 
Test6 323.535235 46.235235  235.2352 

导入 CSV 文件并运行:

$csv = import-csv C:\temp\testfile.csv
foreach ($Item in $csv)
{
$Item.Num1 = [math]::Round($Item.Num1,2)
$Item.Num2 = [math]::Round($Item.Num2,2)
$Item.Num3 = [math]::Round($Item.Num3,2)
}

## To save to new file
$Csv | Export-Csv C:\temp\testfile2.csv -NoTypeInformation

您的输出将是:

Name  Num1     Num2   Num3  
----  ----     ----   ----  
Test1 4.24     346.24 33.24 
Test2 123.35   56.35  326.24
Test3 12424.24 57.35  466.35
Test4 4364.34  12.24  1.12  
Test5 12.55    464.35 346.46
Test6 323.54   46.24  235.24

【讨论】:

  • 不是我要找的金票,但同样好。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多