PowerShell Round & Format Float up to max 2 decimal places?

I found a lot of material for formatting floats to regular known numbers, but how can I format a float to max. 2 decimal places, but only if decimal places are needed?

Examples:

1.11 # not 1.111 1.12 # it was 1.116 (round up) 1.1 # not 1.10 1 # not 1.00 

if i do

  $('{0:N2}' -f $flt) 

I get

  1.00 # :( 

Thanks in advance!

+7
floating-point format powershell
source share
2 answers

Use [math]::round , that is:

 [math]::round(1.111,2) 

will return 1.11 and

 [math]::round(1.00,2) 

gives 1

+16
source share

You can use the # character in a custom number format string to include non-zero digits in the value.

 > 1.001,1.101,1.111 | % { '{0:0.##}' -f $_ } 1 1.1 1.11 

N2 standard number format string is basically equivalent to 0.00 , which produces a fixed number of decimal digits.

+3
source share

All Articles