我正在尝试为我的 android 应用程序创建一个正则表达式,以便将货币格式化为该问题的最佳答案:
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]", "");
StringBuilder cashAmountBuilder = new StringBuilder(userInput);
while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
cashAmountBuilder.deleteCharAt(0);
}
while (cashAmountBuilder.length() < 3) {
cashAmountBuilder.insert(0, '0');
}
cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
cashAmountBuilder.insert(0, '$');
cashAmountEdit.setText(cashAmountBuilder.toString());
}
}
我希望能够具有与该示例相同的格式,仅在数字前减去美元符号,但我真的不确定如何更改该代码来实现它,或者是否有替代方法?
编辑:经过更多评论后,它对我来说很明显,它可能不是我的代码中的这段特殊代码。我可以通过在正则表达式中将美元符号更改为空格并在数字前输入一个空格,稍后在需要该值时对其进行修剪,但我无法找到更好的解决问题。
private TextWatcher billWatcher = new TextWatcher() {
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]", "");
StringBuilder cashAmountBuilder = new StringBuilder(userInput);
while (cashAmountBuilder.length() > 3 && cashAmountBuilder.charAt(0) == '0') {
cashAmountBuilder.deleteCharAt(0);
}
while (cashAmountBuilder.length() < 3) {
cashAmountBuilder.insert(0, '0');
}
cashAmountBuilder.insert(cashAmountBuilder.length()-2, '.');
cashAmountBuilder.insert(0, '$');
billBox.setText(cashAmountBuilder.toString());
billBox.setTextKeepState(cashAmountBuilder.toString());
Selection.setSelection(billBox.getText(), cashAmountBuilder.toString().length());
}
}
盒子的 XML
<EditText
android:id="@+id/billBox"
android:layout_width="152dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_below="@+id/billText"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:digits="0123456789."
android:gravity="right"
android:inputType="numberDecimal" />