簡體   English   中英

使 EditText 只顯示兩位小數

[英]making EditText to show only two decimal places

我想在我的編輯文本中只顯示兩個小數位,ofc 我想在編輯文本中顯示貨幣,但將其值限制為小數點后 2 位。

我已經看到一些使用正則表達式的解決方案,但我不想這樣做。 有人告訴我,java 支持一些可以做到這一點的內部庫函數。 任何人都可以請給我提示或給我一些有效的代碼。

問候

amount.setRawInputType(Configuration.KEYBOARD_12KEY);

         amount.addTextChangedListener(new TextWatcher() 
         {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub
                DecimalFormat formatVal = new DecimalFormat("##.##");
                String formatted = formatVal.format(s);
                amount.setText(formatted);

            }

您可以簡單地使用DecimalFormat

DecimalFormat format = new DecimalFormat("##.##");
String formatted = format.format(22.123);
editText.setText(formatted);

您將在EditText得到結果為22.12

這是一個解決方案,可以在輸入編輯文本時限制用戶。

    InputFilter filter = new InputFilter() {
    final int maxDigitsBeforeDecimalPoint=2;
    final int maxDigitsAfterDecimalPoint=2;

    @Override
    public CharSequence filter(CharSequence source, int start, int end,
            Spanned dest, int dstart, int dend) {
            StringBuilder builder = new StringBuilder(dest);
            builder.replace(dstart, dend, source
                    .subSequence(start, end).toString());
            if (!builder.toString().matches(
                    "(([1-9]{1})([0-9]{0,"+(maxDigitsBeforeDecimalPoint-1)+"})?)?(\\.[0-9]{0,"+maxDigitsAfterDecimalPoint+"})?"

                    )) {
                if(source.length()==0)
                    return dest.subSequence(dstart, dend);
                return "";
            }

        return null;

    }
};

mEdittext.setFilters(new InputFilter[] { filter });

例如,12.22 所以只允許輸入小數點前 2 位和后 2 位。

輸入:

 mBinding.etPriceUpdate.setText = getString(R.string.txt_rupees) + " " + "%.2f".format(firstNum!!.toDouble() * secondNum.toDouble())

輸出:

4567.54 盧比

這會將浮點數 1.23456 格式化為最多 2 個小數位,因為我們在格式化指令 %.2f 中使用了小數點后兩位,f 用於浮點數,它包括 Java 中的 double 和 float 數據類型。 不要嘗試在此處使用“d”表示雙精度數,因為它用於格式化整數並在格式化指令中代表小數。 順便說一下,這里有一個問題,format() 方法也會對數字進行任意舍入。 例如,如果您想將 1.99999 格式化為最多 2 個小數位,那么它將返回 2.0 而不是 1.99,如下所示。

您只需要將setKeyListener()分配給您的EditText

myEditText.setKeyListener(DigitsKeyListener.getInstance(true,true));

返回一個DigitsKeyListener ,它接受數字 0 到 9,加上減號(僅在開頭)和/或小數點(每個字段僅一個)(如果指定)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM