Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Round & Format Float to max 2 decimals?

I found lots of stuff to format floats to common known numbers, but how can I format a float to a max of 2 decimals, but only if the decimals 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!

like image 419
gooly Avatar asked Jun 04 '14 12:06

gooly


People also ask

How do you round numbers in PowerShell?

Rounding in General in PowerShellThe [Math]::Round function accepts two arguments. The first one would be the decimal that the function will round, and the second one would be to which decimal place the integer will be rounded ( 0 for the whole number, 1 for one decimal number, 2 for two decimal number, and so on).

How do I get remainder in PowerShell?

You can use one or more arithmetic operators to add, subtract, multiply, and divide values, and to calculate the remainder (modulus) of a division operation. In addition, the addition operator ( + ) and multiplication operator ( * ) also operate on strings, arrays, and hash tables.

What is BXOR in PowerShell?

The result of -bxor is a number where the bits are set in either the value on the left, or the value on the right, but not both. In the following example, the result is 11 : 6 -bxor 13. This operation can be shown in a table: Bit value.

How do you write a while loop in PowerShell?

PowerShell While loopWrite-Host End of While loop. $var = 1 while ($var -le 5) { Write-Host The value of Var is: $var $var++ } Write-Host End of While loop. $var = 1 while ($var -le 5) { Write-Host The value of Var is: $var $var++ } Write-Host End of While loop.


2 Answers

Use [math]::round, ie:

[math]::round(1.111,2) 

will return 1.11 and

[math]::round(1.00,2) 

yields 1

like image 83
Raf Avatar answered Sep 17 '22 14:09

Raf


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

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

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

like image 25
Emperor XLII Avatar answered Sep 16 '22 14:09

Emperor XLII