Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 发行货币文本格式_Java_Android_Android Edittext_Currency - Fatal编程技术网

Java 发行货币文本格式

Java 发行货币文本格式,java,android,android-edittext,currency,Java,Android,Android Edittext,Currency,所有-我已经为此挣扎了一段时间,并且研究了关于这类事情的所有其他问题,但我就是想不出来:我有一个需要格式化为货币的文本字段。我已经在所有其他与此相关的问题中尝试了该代码,但无论我尝试什么,它都不起作用。这是我的密码: EditText text = (EditText)findViewById(R.id.edit_bill); text.setRawInputType(Configuration.KEYBOARD_12KEY); text.addTextChang

所有-我已经为此挣扎了一段时间,并且研究了关于这类事情的所有其他问题,但我就是想不出来:我有一个需要格式化为货币的文本字段。我已经在所有其他与此相关的问题中尝试了该代码,但无论我尝试什么,它都不起作用。这是我的密码:

EditText text = (EditText)findViewById(R.id.edit_bill);  

    text.setRawInputType(Configuration.KEYBOARD_12KEY);    

    text.addTextChangedListener(new TextWatcher(){
        EditText text = (EditText)findViewById(R.id.edit_bill);
        DecimalFormat dec = new DecimalFormat("0.00");
        public void afterTextChanged(Editable arg0) {
        }
        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().matches("^\\$(\\d{1,3}(\\,\\d{3})*|(\\d+))(\\.\\d{2})?$"))
            {
                String userInput= ""+s.toString().replaceAll("[^\\d]", "");
                if (userInput.length() > 0) {
                    Float in=Float.parseFloat(userInput);
                    float percen = in/100;
                    text.setText("$"+dec.format(percen));
                    text.setSelection(text.getText().length());
                }
            }
        }
    });

此代码位于onClick方法内部。这是否有区别(例如,文本只有在用户单击按钮时才会格式化)?。提前谢谢

我过去曾使用此方法格式化货币

static public String customFormat(String pattern, double s ) {
    DecimalFormat myFormatter = new DecimalFormat(pattern);
    String stringFormatOutput = myFormatter.format(s);
    return stringFormatOutput;
 } 
它可以这样使用:

String strPrice = customFormat("$###,##0.00", 300.2568);
mTxt.setText(strPrice);

只需将“300.2568”更改为您的价格。这可能同样适用于浮点数而不是双倍点数。

不是这样工作的。您无法修改
onTextChanged
中的文本。好的,那么如何将其格式化为货币?后文本改变了吗?