programing

f-string을 사용한 소수점 이후의 고정 자리수

prostudy 2022. 4. 2. 08:58
반응형

f-string을 사용한 소수점 이후의 고정 자리수

Python f-string으로 십진수 이후의 자릿수를 쉽게 고정할 수 있는 방법이 있을까?(특히 f-string, .format 또는 %와 같은 다른 문자열 형식 지정 옵션이 아님)

예를 들어, 소수점 뒤에 두 자리 숫자를 표시한다고 합시다.

그걸 어떻게 하는 거죠?라고 하자.

a = 10.1234

형식 식에 형식 지정자를 포함하십시오.

>>> a = 10.1234
>>> f'{a:.2f}'
'10.12'

에 관한 한float숫자, 형식 지정자를 사용할 수 있음:

f'{value:{width}.{precision}}'

여기서:

  • value숫자로 평가되는 모든 표현식
  • width표시할 총 문자 수를 지정하지만,value너비가 지정한 공간보다 더 많은 공간이 필요한 경우 추가 공간이 사용된다.
  • precision소수점 뒤에 사용된 문자 수를 나타냄

누락된 것은 십진수 값의 유형 지정자입니다.링크에서 부동 소수점 및 소수점에 사용할 수 있는 표시 유형을 찾으십시오.

여기 몇 가지 예를 들자면,f(고정점) 프레젠테이션 유형:

# notice that it adds spaces to reach the number of characters specified by width
In [1]: f'{1 + 3 * 1.5:10.3f}'
Out[1]: '     5.500'

# notice that it uses more characters than the ones specified in width
In [2]: f'{3000 + 3 ** (1 / 2):2.1f}' 
Out[2]: '3001.7'

In [3]: f'{1.2345 + 4 ** (1 / 2):9.6f}'
Out[3]: ' 3.234500'

# omitting width but providing precision will use the required characters to display the number with the the specified decimal places
In [4]: f'{1.2345 + 3 * 2:.3f}' 
Out[4]: '7.234'

# not specifying the format will display the number with as many digits as Python calculates
In [5]: f'{1.2345 + 3 * 0.5}'
Out[5]: '2.7344999999999997'

로비의 대답에 덧붙여 말하자면, 다소 많은 숫자를 인쇄하고 싶은 경우에, 수천 개의 구분자를 사용하는 것이 큰 도움이 될 수 있다(쉼표 참고).

>>> f'{a*1000:,.2f}'
'10,123.40'

고정 너비를 패딩/사용하려는 경우, 너비는 쉼표보다 먼저 이동한다.

>>> f'{a*1000:20,.2f}'
'           10,123.40'

롭의 대답에 덧붙여 f 문자열(여기서 더)과 함께 형식 지정자를 사용할 수 있다.

  • 소수점 수를 제어할 수 있음:
pi = 3.141592653589793238462643383279

print(f'The first 6 decimals of pi are {pi:.6f}.')
The first 6 decimals of pi are 3.141593.
  • 백분율로 변환할 수 있음:
grade = 29/45

print(f'My grade rounded to 3 decimals is {grade:.3%}.')
My grade rounded to 3 decimals is 64.444%.
  • 인쇄 상수 길이와 같은 다른 작업을 수행할 수 있다.
from random import randint
for i in range(5):
    print(f'My money is {randint(0, 150):>3}$')
My money is 126$
My money is   7$
My money is 136$
My money is  15$
My money is  88$
  • 또는 쉼표 천 구분 기호로 인쇄하십시오.
print(f'I am worth {10000000000:,}$')
I am worth 10,000,000,000$
Consider:
>>> number1 = 10.1234
>>> f'{number1:.2f}'
'10.12'
Syntax:
"{" [field_name] ["!" conversion] [":" format_spec] "}"
Explanation:
# Let's break it down...
#       [field_name]     => number1
#       ["!" conversion] => Not used
#       [format_spec]    => [.precision][type] 
#                        => .[2][f] => .2f  # where f means Fixed-point notation

더 나아가 형식 문자열에는 다음과 같은 구문이 있다.보시다시피 할 수 있는 일이 훨씬 더 많다.

Syntax: "{" [field_name] ["!" conversion] [":" format_spec] "}"

# let's understand what each field means...
    field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
    arg_name          ::=  [identifier | digit+]
    attribute_name    ::=  identifier
    element_index     ::=  digit+ | index_string
    index_string      ::=  <any source character except "]"> +
    conversion        ::=  "r" | "s" | "a"
    format_spec       ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]

            # Looking at the underlying fields under format_spec...
            fill            ::=  <any character>
            align           ::=  "<" | ">" | "=" | "^"
            sign            ::=  "+" | "-" | " "
            width           ::=  digit+
            grouping_option ::=  "_" | ","
            precision       ::=  digit+
            type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

https://docs.python.org/3/library/string.html#format-string-syntax을 참조하십시오.

간단히

a = 10.1234
print(f"{a:.1f}")

출력: 10.1

a = 10.1234
print(f"{a:.2f}")

출력: 10.12

a = 10.1234
print(f"{a:.3f}")

출력: 10.123

a = 10.1234
print(f"{a:.4f}")

출력: 10.1234

인쇄할 소수점 표시 뒤에 있는 값을 변경하십시오.

a = 10.1234

print(f"{a:0.2f}")

0.2f 단위로:

  • 0은 python에게 표시할 총 자릿수에 제한을 두지 말라고 말하고 있다.
  • .2는 소수점 이후 2자리만 취하려는 것이다(결과가 반올림함수와 같음)
  • f는 그것이 부동 숫자라고 말하고 있다.f를 잊어버리면 소수점 뒤에 한 자리만 덜 인쇄된다.이 경우 소수점 이후 1자리만 된다.

숫자 https://youtu.be/RtKUsUTY6to?t=606에 대한 f 스트링에 대한 자세한 비디오.

참조URL: https://stackoverflow.com/questions/45310254/fixed-digits-after-decimal-with-f-strings

반응형