PowerShell Round & Format Float to max 2 decimals?

删除回忆录丶 提交于 2020-12-30 04:56:21

问题


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!


回答1:


Use [math]::round, ie:

[math]::round(1.111,2)

will return 1.11 and

[math]::round(1.00,2)

yields 1




回答2:


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.



来源:https://stackoverflow.com/questions/24037021/powershell-round-format-float-to-max-2-decimals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!