Trying to modify output to 2 decimal places

Hello!
I am trying to change output of this to be 2 dec places:
dir c:\ -Recurse -File | sort-object -property length | select name, @{Name='Length (GB)';Expression={$_.Length / 1GB}} -last 10

I have tried inserting '{0:F2}' -f before the {$_.Length / 1GB}
But thats not working

I was thinking of using [Math]::round somehow…

Im still learning, can someone show me how to change that calculated property?

Thanks!

Matthew,
Welcome to the forum. :wave:t4:

It does work … if you do it right … :wink:

Don’t just think about - do it. :wink:

Depending on what you actually want you can do both … while the format way might end up in unprecise results it probably will be precise enough in most cases I think. So its a matter of personal preference or taste wich one you use. Another side effect using the format way is that the results become strings. If you want to use the results later on for some calculation you should go with the proper [Math] way. :wink:

Get-ChildItem -Path c:\ -Recurse -File | 
    Sort-Object -Property length | 
        Select-Object -Last 10 -Property name, 
            @{Name = 'Length (GB formatted)'; Expression = {'{0:F2}' -f ($_.Length / 1GB)}} ,
            @{Name = 'Length (GB rounded)'; Expression = {[Math]::Round($_.Length / 1GB, 2)}} 

Using a GB unit might cause all small files displayed as 0.00 in length. :point_up_2:t4:

Regardless of that - using aliasses in scripts or in forums is considered very bad style. Please avoid using them.

And BTW: When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

How to format code in PowerShell.org <---- Click :point_up_2:t4: :wink:

Thanks Olaf!

btw - where did I use an alias? My code originally had the Name with an ‘n’ and the Expression with an ‘e’, I replaced those!

dir is the alias for Get-ChildItem :wink:

You can list all aliasses with

Get-Alias

It is recommended to write your code as verbose as possible to make it easily readable.

Here you can read more about this topic:

Olaf,
I missed that dir. Thanks again!

Matt

Hi Olaf,
I was dissecting your words and am slightly confused. You say:

Another side effect using the format way is that the results become strings. If you want to use the results later on for some calculation you should go with the proper [Math] way.

In the code, the Math way is labeled formatted.
Is the one that uses {0:F2} the one that becomes a string?

Thanks!

Ooops … my mistake. :man_shrugging:t4: I already corrected the code above. :wink:

Yes. Of course. :+1:t4:

It’s late. I go to bed now.

Good night. :sleeping:

1 Like