본문 바로가기
컴퓨터 & IT (Computer & IT)/Windows and Powershell

[PowerShell] float 및 Double 소수점 출력

by Physics 2021. 1. 26.
728x90

PowerShell에서 Float 혹은 Double 변수의 string format을 지정하는 방법은 아래와 같다. 

1. .ToString() method 사용 [1]

ToString() method를 사용하는 방법은 다음과 같다: <variable>.ToString(#.###) 
   - #.###: digit이 사라지는 지점을 명시적으로 표기. 
   - digit이 사리지는 지점은 반올림하여 표기함. 

ex) 예시 

>>> $example = 123.45678
>>> $example.ToString("#.#")
123.5
>>> $example.ToString("#.##")
123.46
>>> $example.ToString("#.###")
123.457

2. [math]::Round() Method 이용 [2]

[math]::Round() method를 사용하는 방법은 다음과 같다: [math]::Round(variable, n)  
   - n: 반올림할 자리수 

>>> $example = 123.456789
>>> [math]::Round($example, 2)
123.46
>>> [math]::Round($example, 3)
123.457
>>> [math]::Round($example, 4)
123.4568

 

3. -f Format operator [3]

-f Format operator의 syntax는 아래와 같다: "string {I,A:FS}" -f <Array of values>  
  (1) I: Index of the item to display, 0, 1, 2, etc 
  (2) A: Alignment
          - A positive number will right align n characters. 
          - A negative number will left align n characters. 
          - C 언어의 printf와 비교를 하면 "%nd", "%nf"의 "n"의 역활과 동일하다. ( 공백을 주는 역활)
  (3) FS: options 

options Description
:c Currency format (for the current culture)
:e Scientific (exp) notation
:f Fixed point
:f5 = fix to 5 places
:g Most compact format, fixed or sci
:g5 = 5 significant digits
:n Number (:nP precision=number of decimal places)
:p Percentage
:r Reversible Precision
:x Hex Format
# Digit Place Holder
날짜와 관련된 옵션
:hh
:mm
:ss
Convert a DateTime to a 2 digit Hour/minute/second
"{0:hh}:{0:mm}"
:HH Hour in 24 Hour format
:dd Day of Month
:ddd Convert a DateTime to Day of the Week
:dddd Full name of Day of Weak
:yyyy Full year

 - 자세한 옵션에 대한 설명은 아래 레퍼런스를 참조하길 바란다. [3] 
 - Float 및 Double 형을 String으로 변환 후 우리가 원하는 소수점까지 표현하는데 필요한 옵션들을 분홍색으로 칠해진 옵션을 보면 된다. 

아래는 위 옵션을 사용한 예시이다.
※ 해당 옵션을 사용하면 버리는 소수점 이하는 반올림이 되어서 출력이 됨. 

>>> $example = 123.456789
>>> "{0:n2}" -f $example
123.46
>>> "{0:n3}" -f $example
123.457
>>> "{0:n4}" -f $example
123.4568

>>> $example = 123.456789
>>> "{0:f2}" -f $example
123.46
>>> "{0:f3}" -f $example
123.457
>>> "{0:f4}" -f $example
123.4568

>>> $example = 123.456789
>>> "{0:#.##}" -f $example
123.46
>>> "{0:#.###}" -f $example
123.457
>>> "{0:#.###}" -f $example
123.4568

 

 

Reference: 
[1] devblogs.microsoft.com/scripting/formatting-powershell-decimal-places/   
[2] devblogs.microsoft.com/scripting/powertip-use-powershell-to-round-to-specific-decimal-place/
[3] www.powershell.co.at/number-formatting-with-the-format-operator-f-on-powershell-7/  

728x90

댓글