Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

powershell Trying to format a csv file column to a given number of decimal places

I have a csv column called Volume that I am trying to reformat to a given number of decimal places. Here is what I have from ChatGPT but I am getting errors:
The property cannot be processed because the property "Volume" already exists.

$data = Import-Csv $AF
$columnName = "Volume"
$numberOfDecimalPlaces = 2

# Format the column with the specified number of decimal places
$newData = $data | Select-Object *,@{
    Name = $columnName
    Expression = { "{0:N$numberOfDecimalPlaces}" -f [decimal]$_.$columnName }
}

$newData | Export-Csv $AF -NoTypeInformation

Any help in formatting the column would be appreciated. I have a number of them to format.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

By using *,@{Name='Volume', ...} you are telling it to use "All the Columns, including Volume, AND then also add ANOTHER ‘Volume’ column"

# Load CSV file in a collection
$Csv = Import-Csv $File

# self-loop through the collection, changing the value as you need
# BEWARE: the decimal separator will be in the style of the [cultureinfo]::currentculture value
$Csv.Foreach({ $_.$Column= "{0:N$numberOfDecimalPlaces}" -f [decimal]$_.$Column})

# export back the collection
# you can skip -NoTypeInformation if you are using Powershell 6+
$Csv | Export-Csv -Path $File -NoTypeInformation
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading