Android Money Input with fixed decimal

后端 未结 7 1236
鱼传尺愫
鱼传尺愫 2020-12-02 00:07

How do you create an edittext entry that formats input in money format only? When the user enters 5, I want the input to look like \"$0.05\" and when they then enter 3, th

相关标签:
7条回答
  • 2020-12-02 00:41

    This answer is based on Zds' answer (which in turn was based on ninjasense's answer), but this should resolve the cursor position issue:

    if(!text.matches("^\\$(\\d{1,2})(\\.\\d{2})?$")) {
        int originalCursorPosition = view.getSelectionStart();
        int cursorOffset = 0;
    
        boolean cursorAtEnd = originalCursorPosition == text.length();
    
        String userInput= ""+text.replaceAll("[^\\d]", "");
        StringBuilder cashAmountBuilder = new StringBuilder(userInput);
    
        while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0')           {  
            cashAmountBuilder.deleteCharAt(0);
            cursorOffset--;
        }
        while (cashAmountBuilder.length() < 3) {
            cashAmountBuilder.insert(0, '0');
            cursorOffset++;
        }
        cashAmountBuilder.insert(cashAmountBuilder.length() - 2, '.');
        cashAmountBuilder.insert(0, '$');
    
        view.setText(cashAmountBuilder.toString());
        view.setSelection(cursorAtEnd ? view.getText().length() : originalCursorPosition + cursorOffset);
    }
    

    Notes:

    • The following is in a TextWatcher.onTextChanged
    • I'm using a different regex than other answers, which keeps the price to < $100
    • 'view' is the editText, 'text' is the string contents
    • this has worked for me using an EditText with a maxLength of 6 (i.e. $00.00)
    0 讨论(0)
提交回复
热议问题