Java/순수 Java

[Java] n번째 소숫점 자리 출력

기은P 2020. 5. 11. 16:37
반응형

[Java] n번째 소숫점 자리 출력

 

 

1. 주요 코드

 

private double updateIndex = 0;
updateIndex += (Math.random() * 0.1);
updateIndex += 0.1;
System.out.println(String.format("%.5f", updateIndex));

 

소숫점 자리로 출력하려면 당연히 int가 아닌 float이나, long, double 같은 자료형을 사용해야 한다.

여기서 중요한 것은 String.format()함수.

%.5f가 즉 5번째 자리까지 출력한다는 의미이다.

%.3f를 넣었다면 3번째 자리까지 소숫점이 출력된다.

 

 

현재 updateIndex라는 변수는 Math.random()값에 0.1을 곱하고, 0.1을 더한 값으로 초기화를 했다.

 

 

 

2. 예시 코드

 

public static Runnable updater;
private static double updateIndex = 0;
static boolean running = false;
private static boolean plus = false;

public void run(){
		updater = new Runnable() {
			public void run() {
//				System.out.println(t);

				if (plus == false) {
					updateIndex += (Math.random() * 0.1);
					plus = true;
					updateIndex += 0.1;

				} else {
					updateIndex -= (Math.random() * 0.1);
					plus = false;
					updateIndex -= 0.1;
				}
				System.out.println(String.format("%.5f", updateIndex));

				if (running) {
					Display.getCurrent().timerExec(1000, this);
				}
			}
		};

		Display.getCurrent().timerExec(1000, updater);
		running = true;
}

 

Thread를 이용해 1초마다 updateIndex의 값이 0.1*랜덤값+0.1로 변동이 있게끔 설정했다.

 

 

 

3. 실행 결과

 

필자는 GEF Nebula 기반의 Chart Viewer를 사용하고 있었기 때문에 위와 같이 그래프가 갱신되는 것을 확인해 볼 수 있다.

 

 

 

코드 상에서 확인해보면 소숫점 5자리까지 나오는 것을 확인해 볼 수 있다.

 

반응형