2026/02/12

오늘의 이야기

자료출처 : stackoverflow.com/questions/26533347/format-currency-string-using-edittext-in-android



 


Format currency string using EditText in Android


I'm trying to format the input value of an EditText in Android, I want to format the input in currency value, I' ve tried the following: EditText minimo = (EditText) view.findViewById(R.id.


stackoverflow.com




 


어느 분의 요청으로 앱에 숫자 입력을 마치 계산기 처럼 숫자를 입력하면 3자리 마다 콤마가 나오게 하는 방법을 찾아 보다가 위의 링크를 보게 되었다.


 


import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

import java.text.DecimalFormat;
import java.text.ParseException;

public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;

private EditText et;

public NumberTextWatcher(EditText et)
{
df = new DecimalFormat("#,###.##");
df.setDecimalSeparatorAlwaysShown(true); // 소숫점 이하를 표시할 까 ?
dfnd = new DecimalFormat("#,###");
this.et = et;
hasFractionalPart = false; // 분수여부 ?
}

@SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";

public void afterTextChanged(Editable s)
{
et.removeTextChangedListener(this);

try {
int inilen, endlen;
inilen = et.getText().length();

// 입력된 값에서 숫자만 추출
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
// 소숫점 입력 여부에 따라서
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}

// 전체 입력된 길이를 기준으로 해서
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
// 한글짜씩 추가 하는 형식으로 처리
if (sel > 0 && sel <= et.getText().length()) {
et.setSelection(sel);
} else {
// place cursor at the end?
et.setSelection(et.getText().length() - 1);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}

et.addTextChangedListener(this);
}

public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}

public void onTextChanged(CharSequence s, int start, int before, int count)
{
// 소숫점이 입력 되는 지를 체크
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator())))
{
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}

 


대강 필요한 부분의 기능을 살펴 보면 위에 소스에 달아 놓은 코멘트와 같지 않을 까 싶다.


 


그리고 layout 에서 주의할 것은 EditText 의 gravity 을 end 로 설정해서 입력하는 숫자가 오른쪽 끝에서 입력이 되도록 설정을 해야 내가 만든 앱에서 입력이 계산기 처럼 숫자가 입력될 때 표시가 되는 효과를 느낄 수 있다.


 





댓글 없음:

댓글 쓰기

오늘의 이야기

이 앱은  작은 정비업소등에서 사용할 수 있도록 개발된 앱입니다.   1. 이앱은 5가지 정도의 공정을 가지고 있는 정비업소에서 각 공정별로 입고되는 수리대상 품목(이하 수리차량이라 명칭)을 입고, 도장, 하부, 판금, 점검 등의 구분에 따라 관리할 ...