Convert the number 1 to 1.0

Hello,

I have a variable $a = 234 and I need it to be displayed as 234.0. what are the possible ways ?
It shouldn’t be converted to string

Please help

Rahul,

Welcome to the forums.

You may elaborate a little more detailed what it is about. Because when you say “to be displayed” it shouldn’t matter if the number is a string - it is only for DISPLAY. :wink:
If you need to convert an integer to a float to calculate with it you can simply cast it to.

$a -as [Single]

… for example. But that wouldn’t change how PowerShell shows it on the console as long as it does not have numbers after the decimal point.

Hello Olaf,

Thanks for your answer, but I still get the answer as 234, I am trying to get the result to limit to one decimal place even for an integer.

this way,
234 => 234.0
29.1 => 29.1

That’s what I meant. PowerShell does not output what’s actually not there. You will have to force it by converting it to a string … like this for example:

$a = 234
'This would be the output you desire: {0:n1}' -f $a

Again … you may elaborate a little more detailed what it is you ACTUALLY want to achieve. :wink:

1 Like

Thanks Olaf,
Trying to explain explain what I am trying to do …

I have a script that will get the list of folders from path provided and it uses Convert-Size script for converting the Size to appropriate results automatically.

$size | Convert-Size

It converts to string I believe. And the results of the script is as shown below when sorted with Size in Descending

FolderName. Size
___________. ________________
Seoh 511 MB
Sepef 51.7 MB
Svp 51.2 MB
Lisam2. 507 MB

But, they are not properly sorted. So I would like to convert the result of $size to float with one decimal place, assuming it will solve my problem of sorting

Any other idea will also be appreciated

Hmmm … I doupt that it is that easy. :wink: … as long as you want to output the numbers along with the size unit you would need to sort it BEFORE outputting it to the console. Another straight forward solution would be to name the column like this: "Size(MB)" and ouput the raw sizes. :wink:

1 Like

@Rahul20, unlike other floating point numeric types, trailing zeros are kept due to the scale. But in PowerShell, showing the trailing zeros while keeping the value a decimal is not easy, if at all possible.

The scaling factor also preserves any trailing zeros in a Decimal number. Trailing zeros do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeros might be revealed by the ToString method if an appropriate format string is applied.

(Decimal Struct (System) | Microsoft Learn)

As @Olaf said, if you are displaying information, sort the numeric values first, and then format the data as strings for the output.

The following takes an array of decimal values, sorts them, then outputs the formatted string value of each member. You can add a [math] conversion in the ForEach-Object prior to the ToString().

[decimal[]]$nbrs = 51.1,32.02,234,88.32 | Sort-Object | ForEach-Object {$_.ToString("F1")}

–This proof is not presented as a solution.

Note: truncation occurs.

1 Like

Yeah Olaf, Thanks for the clarification. I was thinking of the same way So what I did is below:

$tmp = $size|convert-size
$sizeValue= $tmp.split(" “)[0]
$sizeUnit = $tmp.split(” ")[1]

Now, I have added the size value and size unit in the PSCustomObject, which is showing results like below:

$results|?{$_.SizeValue -gt “50”}|sort -property SizeValue -Descending

FolderName         SizeValue          SizeUnit
-----------------   -------------   --------------
Seoh                 511                MB
Lisam2.              507                MB
Sepef                51.7               MB
Svp                  51.2               MB
type or paste code here

thanks @dicey.

From your answer, I came to know an argument for “ToString” Method that can be used.

Can you let me know what are the available arguments that can be used in the ToString and ToDecimal methods.

And I tried the below, but it works only for numbers already having decimal places

$a.ToString(“#.#”)

Hmmm … that’s actually not what I had in my mind. :wink: … How do you fill in your variable $Size

? And what does you function Convert-Size do? (you might show the code)

If I’m allowed to say that - I don’t like the look of that. I’d rather do it this way:

FolderName         SizeValue(MB)
-----------------   -------------
Seoh                 511
Lisam2.              507
Sepef                51.7
Svp                  51.2

Another solution would be to sort it before you add the size units.

@Olaf, actually the base folder that I am working has size in MB and GB as well, so I wanted to distinguish easily. Instead of showing more than 1024 MB, I did that way.

Below is the convert-size function full code, which converts the size. :slight_smile:

Function Convert-Size {

<#

    .SYNOPSIS
        Converts a size in bytes to its upper most value.

    .DESCRIPTION
        Converts a size in bytes to its upper most value.

    .PARAMETER Size
        The size in bytes to convert

    .EXAMPLE
    Convert-Size -Size 568956
    555 KB

    Description
    -----------
    Converts the byte value 568956 to upper most value of 555 KB

    .EXAMPLE
    Get-ChildItem  | ? {! $_.PSIsContainer} | Select -First 5 | Select Name, @{L='Size';E={$_ | Convert-Size}}
    Name                                                           Size                                                          
    ----                                                           ----                                                          
    Data1.cap                                                      14.4 MB                                                       
    Data2.cap                                                      12.5 MB                                                       
    Image.iso                                                      5.72 GB                                                       
    Index.txt                                                      23.9 KB                                                       
    SomeSite.lnk                                                   1.52 KB     
    SomeFile.ini                                                   152 bytes   

    Description
    -----------
    Used with Get-ChildItem and custom formatting with Select-Object to list the uppermost size.          
#>
[cmdletbinding()]
Param (
    [parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
    [Alias("Length")]
    [int64]$Size
)
Begin {
    If (-Not $ConvertSize) {
        Write-Verbose ("Creating signature from Win32API")
        $Signature =  @"
             [DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]
             public static extern long StrFormatByteSize( long fileSize, System.Text.StringBuilder buffer, int bufferSize )"@
        $Global:ConvertSize = Add-Type -Name SizeConverter -MemberDefinition $Signature -PassThru
    }
    Write-Verbose ("Building buffer for string")
    $stringBuilder = New-Object Text.StringBuilder 1024
}
Process {
    Write-Verbose ("Converting {0} to upper most size" -f $Size)
    $ConvertSize::StrFormatByteSize( $Size, $stringBuilder, $stringBuilder.Capacity ) | Out-Null
    $stringBuilder.ToString()
}

}

OK, I don’t have time at the moment to deep dive into that code but here is something I found time ago and it might be helpful for you.

$Path = 'd:\sample\files'
Get-ChildItem -Path $Path -File |
Select-Object -Property *,@{
Name = 'ReadableSize';
Expression = {
        $size = $_.Length;
        $postfixes = @( "B", "KB", "MB", "GB", "TB", "PB" )
        for ($i = 0; $size -ge 1024 -and $i -lt $postfixes.Length; $i++) { $size = $size / 1024; }
        return "" + [System.Math]::Round($size, 2) + " " + $postfixes[$i]; 
    }
} |
Sort-Object -Property Length |
    Select-Object -Property Name,ReadableSize

As you can see I am adding an additional property in the first place, sort the output by the standard property lenght and limit the output to only the properties I need.

That’s what I meant with:

:wink:

1 Like