본문으로 바로가기

반올림

category Python 프로그래밍/코드업 기초 100제 2022. 3. 3. 13:26

6042 : [기초-값변환] 실수 1개 입력받아 소숫점이하 자리 변환하기(설명)(py)

기재된 함수 : format함수를 사용한 반올림

내가 먼저 생각 난 함수 : round 함수를 사용한 반올림

c

#include <math.h> 할거 아니면

printf("%.2f", myfloat);

python

a=float(input())
print( format(a, ".2f") )

print( round(3.14159, 2) )  # 3.14

java

Math.round()함수는 소수점아래가 0일경우 절삭하지만 String.format은 절삭하지 않고 그대로 리턴합니다.

Math.round()함수 썼을 때 : 

double pie = 3.14159265358979;

System.out.println(Math.round(pie)); //결과 : 3

System.out.println(Math.round(pie*100)/100.0); //결과 : 3.14

System.out.println(Math.round(pie*1000)/1000.0); //결과 : 3.142

String.format 썼을 떄 : 

double pie = 3.14159265358979;

double money = 4424.243423;

System.out.println(String.format("%.2f", pie)); //결과 : 3.14

System.out.println(String.format("%.3f", pie)); //결과 : 3.142

System.out.println(String.format("%,.3f", money)); //결과 : 4,424.243