powershellformatting

Formatting an integer x.xxxxx as xx.xxx


I have a number, $int,

$int = 9.5587452369

I want this number to be in the format xx.xxx I tried:

$int = "{0:N3}" -f ($int)
$int = "{0:D2}" -f ($int)

or

$int = "{0:D2}" -f ("{0:N3}" -f ($int))

But it doesn't work. Any Ideas?


Solution

  • Use the toString() method with specified format.

    PS > $int = 9.5587452369
    PS > $int.ToString("00.000")
    09,559
    

    Or

    PS > "{0:00.000}" -f $int
    09,559 
    

    Read more at MSDN - Custom Numeric Format Strings