๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Language/Python

[๋ฌธ๋ฒ•] ์†Œ์ˆ˜์  ์ž๋ฆฌ ์ œํ•œํ•˜๊ธฐ

 

 ๐Ÿ’ก ์†Œ์ˆ˜์ ์ž๋ฆฌ ์ œํ•œ๋ฐฉ๋ฒ• (3๊ฐ€์ง€)

  1. โ€‹round ๋ฉ”์†Œ๋“œ
  2. format ์„œ์‹ ์ง€์ •
  3. f-string ํฌ๋งคํŒ…

โ€‹

 

 

 ๋ฐฉ๋ฒ• 1. round ๋ฉ”์†Œ๋“œ

๐Ÿ‘‰ round (๋ฐ˜์˜ฌ๋ฆผํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฐ’, ์ž๋ฆฟ์ˆ˜)

a = round(1.23456)
b = round(1.23456, 0)
c = round(1.23456, 1)
d = round(1.23456, 2) 
e = round(1.23456, 3)
f = round(1.23456, 4)
print(f"round(1.23456) : {a}") 		# ๊ฒฐ๊ณผ : 1
print(f"round(1.23456, 0) : {b}") 	# ๊ฒฐ๊ณผ : 1.0
print(f"round(1.23456, 1) : {c}")	# ๊ฒฐ๊ณผ : 1.2
print(f"round(1.23456, 2) : {d}")	# ๊ฒฐ๊ณผ : 1.23
print(f"round(1.23456, 3) : {e}")	# ๊ฒฐ๊ณผ : 1.235
print(f"round(1.23456, 4) : {f}")	# ๊ฒฐ๊ณผ : 1.2346

 

 

 

 ๋ฐฉ๋ฒ• 2. format ์„œ์‹ ์ง€์ •

๐Ÿ‘‰  "{ : .์ •์ˆ˜f}".format(์‹ค์ˆ˜)

a = "format example1 : {:.2f}".format(1.23456789)	
b = "format example2 : {:.2f} / {:.3f}".format(1.23456789, 3.456789)  
c = "format example3 : {0:.2f} / {1:.1f}".format(3.22521321, 10.123456) 
d = "format example4 : {1:.2f} / {0:.1f}".format(3.22521321, 10.123456)


print(a)		# ๊ฒฐ๊ณผ : 1.23
print(b)		# ๊ฒฐ๊ณผ : 1.23 / 3.457
print(c)		# ๊ฒฐ๊ณผ : 3.23 / 10.1
print(d)		# ๊ฒฐ๊ณผ : 10.12 / 3.2

 

 

 

 ๋ฐฉ๋ฒ• 3. f-string ํฌ๋งคํŒ…

๐Ÿ‘‰  f "{๋ณ€์ˆ˜ : .์ •์ˆ˜f}"

num1 = 1.23456789 
num2 = 9.87654321
print(f'f-string example1 : {num1:.0f}') 		#๊ฒฐ๊ณผ : 1
print(f'f-string example2 : {num1:.1f}')  		#๊ฒฐ๊ณผ : 1.2
print(f'f-string example3 : {num1:.2f}') 		#๊ฒฐ๊ณผ : 1.23
print(f'f-string example4 : {num1:.3f}')  		#๊ฒฐ๊ณผ : 1.235
print(f'f-string example5 : {num1:.4f}') 		#๊ฒฐ๊ณผ : 1.2346
print(f'f-string example6 : {num2:.0f}') 		#๊ฒฐ๊ณผ : 10
print(f'f-string example7 : {num2:.1f}')  		#๊ฒฐ๊ณผ : 9.9
print(f'f-string example8 : {num2:.2f}') 		#๊ฒฐ๊ณผ : 9.88
print(f'f-string example9 : {num2:.3f}') 		#๊ฒฐ๊ณผ : 9.877
print(f'f-string example10 : {num2:.4f}') 		#๊ฒฐ๊ณผ : 9.8765

 

728x90