Java 在3个字符后添加空格

Java 在3个字符后添加空格,java,android,android-edittext,android-progressbar,Java,Android,Android Edittext,Android Progressbar,我有一个seekbar,它在进展到EditText时将值设置为1500到48500。我想在进度更改后添加一个空格,例如1500变为1500、1600、30000、48500。我怎样才能做到这一点。我的意思是格式化进行的数字,以便在3个字符后设置一个空格 这是我的工作 decimalFormat = new DecimalFormat("0 000"); SeekBar mSeekbar = (SeekBar) findViewById(R.id.seekvalue); mSeekba

我有一个seekbar,它在进展到EditText时将值设置为1500到48500。我想在进度更改后添加一个空格,例如1500变为1500、1600、30000、48500。我怎样才能做到这一点。我的意思是格式化进行的数字,以便在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) {}
    });

类似的东西应该可以使用自制的实现。我没有测试这个,因为我没有在这台计算机上运行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

   }
}
String s=“1000”;
字符串temp=“”;
如果(s.length>=4){//如果长度小于4,则不执行任何操作
对于(int i=0;i
您可以使用类。我没有得到实际的正则表达式来执行它,所以我是这样做的(请注意
null
String):


我会用十进制。下面应该可以做到这一点:

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

这将提供10000个

我添加这个答案有点晚了,我知道。但对于像我这样的人来说,他们陷入了这一困境,想要一种比使用正则表达式更干净的方法:

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

您必须在最后调用
setDecimalFormatSymbols()
,因为
getDecimalFormatSymbols()
克隆了
DecimalFormat
使用的对象签出,您有什么问题吗?我想在每3位数字后设置一个空格,例如1500到1500,您的问题是?在你的问题中,你说它工作正常,马可不介意,谢谢你的回答。空字符串将导致一个力关闭。如何使用它。
DecimalFormat formatter = new DecimalFormat("###,###,###,###");
DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
formatter.setDecimalFormatSymbols(symbols);