Programing

소수점 이하 두 자리 만 표시

lottogame 2020. 9. 22. 20:59
반응형

소수점 이하 두 자리 만 표시 [중복]


이 질문에 이미 답변이 있습니다.

소수점 이하 두 자리의 double 값을 얻는 방법.

예를 들면

만약

i=348842.
double i2=i/60000;
tv.setText(String.valueOf(i2));

이 코드 생성 5.81403333.

하지만 나는 5.81.

그래서 내가 무슨 소리를하는지?


DecimalFormat을 사용하십시오 .

DecimalFormat은 십진수 형식을 지정하는 NumberFormat의 구체적인 하위 클래스입니다. 서양, 아랍어 및 인도 숫자 지원을 포함하여 모든 로케일에서 숫자를 구문 분석하고 형식을 지정할 수 있도록 설계된 다양한 기능이 있습니다. 또한 정수 (123), 고정 소수점 숫자 (123.4), 과학적 표기법 (1.23E4), 백분율 (12 %), 통화 금액 ($ 123) 등 다양한 종류의 숫자를 지원합니다. 이들 모두를 현지화 할 수 있습니다.

코드 스 니펫 -

double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));

출력 -

5.81


어때요 String.format("%.2f", i2)?


여기서는 소수점을 더 짧게 만드는 방법을 보여줄 것입니다. 여기서는 소수점 이하 4 값으로 줄입니다.

   double value = 12.3457652133
  value =Double.parseDouble(new DecimalFormat("##.####").format(value));

가장 좋고 간단한 해결책은 (KISS)입니다.

double i = 348842;
double i2 = i/60000;
float k = (float) Math.round(i2 * 100) / 100;

형식화하는 대신 값을 반환합니다.

double number1 = 10.123456;
double number2 = (int)(Math.round(number1 * 100))/100.0;
System.out.println(number2);

i=348842.
double i2=i/60000;
DecimalFormat dtime = new DecimalFormat("#.##"); 
i2= Double.valueOf(dtime.format(time));
v.setText(String.valueOf(i2));

First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.

And other aspect is providing proper result. So you want to truncate the number or round it.

So before you start you should ask your self, am i interested on the value or not.

To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.

참고URL : https://stackoverflow.com/questions/10959424/show-only-two-digit-after-decimal

반응형