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!
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).
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.
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.
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.
Use [math]::round
, ie:
[math]::round(1.111,2)
will return 1.11
and
[math]::round(1.00,2)
yields 1
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With