【问题标题】:Add a space after 3 characters在 3 个字符后添加一个空格
【发布时间】:2013-05-07 12:17:32
【问题描述】:

我有一个搜索栏,它在进入 EditText 时将值设置为 1500 到 48500。我想在更改进度的每 3 个字符后添加一个空格,例如 1500 变为 1 500、1 600、30 000、48 500。我该如何实现这一点。我的意思是格式化进度数字,以便在 3 个字符后设置一个空格。

这是我的工作

decimalFormat = new DecimalFormat("0 000");

SeekBar mSeekbar = (SeekBar) findViewById(R.id.seekvalue);

    mSeekbar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
    {
       public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
       {

           progress = progress + 1500;

        edt_validate.setText(decimalFormat.format(Integer.toString(progress)));
         //edt_validate.setText(Integer.toString(progress + 1500));

       }

      public void onStartTrackingTouch(SeekBar seekBar) {}

      public void onStopTrackingTouch(SeekBar seekBar) {}
    });

【问题讨论】:

  • 你的问题是什么?
  • 我想在每 3 位数字后设置一个空格,例如1500 到 1 500
  • 你的问题是?在你的问题中你说它正在工作
  • 没关系,Marco 不介意,感谢您的回复

标签: java android android-edittext android-progressbar


【解决方案1】:

您可以使用DecimalFormat 类。我没有真正的正则表达式来做,所以我这样做了(请注意null String):

DecimalFormat df = new DecimalFormat("#,###,###");
edt_validate.setText(df.format(progress).replaceAll(",", " ")));

【讨论】:

  • Yes null String 会导致强制关闭
【解决方案2】:

我会使用 DecimalFormat。以下应该可以解决问题:

int numberToFormat = 10000;
DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance((Locale.getDefault()));
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
String formattedResult = formatter.format(numberToFormat).replaceAll(","," ");

这将给 10 000

【讨论】:

    【解决方案3】:

    这样的事情应该可以使用自制的实现。我没有对此进行测试,因为我没有在这台计算机上运行 eclipse,所以它可能需要一些微调

    String s ="1000";
    String temp="";
    if(s.length>=4){ // do nothing if length is less then 4
       for (int i = 0; i < s.length(); i++){
           if(i%3=0){ // every third char, add a space along with the value in s
              temp.charAt(i)=" "; //first add the space
              temp.charAt(i+1)=s.charAt(i); // then add the char at the next index
              }
           else
              temp=s.charAt(i); // If its not a "third char" just add it without the space
    
       }
    }
    

    【讨论】:

      【解决方案4】:

      我知道我添加这个答案有点晚了。但是为了像我这样的人陷入这个线程并想要一种比使用正则表达式更清洁的方式:

      DecimalFormat formatter = new DecimalFormat("###,###,###,###");
      DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
      symbols.setGroupingSeparator(' ');
      formatter.setDecimalFormatSymbols(symbols);
      

      您必须在最后调用setDecimalFormatSymbols(),因为getDecimalFormatSymbols() 克隆了DecimalFormat 使用的对象。

      【讨论】:

      • 这个怎么用。
      猜你喜欢
      • 2015-05-26
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 2014-04-17
      相关资源
      最近更新 更多