Bigi201110141
Enthusiast
Enthusiast

Decimal round of size

Jump to solution

Here is a portion of my script. Can someone please assist with the rounding of the sizemb on the last line

When I run this I am getting the following

34.457454758739874837483

I would like it to round of to the nearest MB or 1 decimal place (either 34MB or 34.5MB)

Big Thanks.

$VMsWithSnaps = @(Get-VM | Get-Snapshot | Select vm,name,sizemb)

if($VMsWithSnaps -ne $null){

  $body = @("

  <center><table border=1 width=60% cellspacing=0 cellpadding=8 bgcolor=Black cols=3>

  <tr bgcolor=White><td>Virtual Machine</td><td>Snapshot</td><td>Size in MB</td></tr>")

  $i = 0

  do {

  if($i % 2){$body += "<tr bgcolor=#D2CFCF><td>$($VMsWithSnaps[$i].VM)</td><td>$($VMsWithSnaps[$i].Name)</td><td>$($VMsWithSnaps[$i].Sizemb)</td></tr>";$i++}

1 Solution

Accepted Solutions
mattandes
Enthusiast
Enthusiast

Try replacing this line:


$VMsWithSnaps = @(Get-VM | Get-Snapshot | Select vm,name,sizemb)


With this:


$VMsWithSnaps = @(Get-VM | Get-Snapshot | Select vm,name,@{N="SizeMB";E={[math]::round($_.SizeMB, 1)}})

Blog: http://www.virtual-matt.net

View solution in original post

0 Kudos
8 Replies
mattandes
Enthusiast
Enthusiast

Try replacing this line:


$VMsWithSnaps = @(Get-VM | Get-Snapshot | Select vm,name,sizemb)


With this:


$VMsWithSnaps = @(Get-VM | Get-Snapshot | Select vm,name,@{N="SizeMB";E={[math]::round($_.SizeMB, 1)}})

Blog: http://www.virtual-matt.net
0 Kudos
ChrisJ615
Enthusiast
Enthusiast

Here you go:

$VMsWithSnaps = @(Get-VM | Get-Snapshot | Select vm,name,{[int]$_.sizemb})

Give this a read if you get a moment.  It explains how [int] works Smiley Happy Windows PowerShell Tip: Formatting Numbers

LucD
Leadership
Leadership

Casting to an [int] doesn't do rounding afaik


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
ChrisJ615
Enthusiast
Enthusiast

Sure it does:

PS C:\Users\chris> $test = 34.457454758739874837483

PS C:\Users\chris> [int]$test

34

PS C:\Users\chris>

Smiley Happy

0 Kudos
LucD
Leadership
Leadership

To an [int] yes, but not to a decimal, that's why you use [math]::round


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
ChrisJ615
Enthusiast
Enthusiast

Correct - [int] uses the .Net method MidpointRounding Enumeration (System).  But whole numbers are a good thing, right. Smiley Wink

Either way the requirement was:

I would like it to round of to the nearest MB or 1 decimal place (either 34MB or 34.5MB)

I guess we both win. :smileycool:

0 Kudos
LucD
Leadership
Leadership

There are no winners in this community, only users that get their questions answered 😉


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

Bigi201110141
Enthusiast
Enthusiast

Big Thanks. Both solutions worked.

0 Kudos