在某个位置插入一个string

我得到一个6位数的整数。 我想要显示它作为一个String与小数点(。)在2位数字的结尾。 我想使用float但build议使用String更好的显示输出(而不是1234.51234.50 )。 因此,我需要一个函数,将采取一个int作为参数,并返回格式正确的String从小数点2位数字结束。

说:

 int j= 123456 Integer.toString(j); //processing... //output : 1234.56 
 int j = 123456; String x = Integer.toString(j); x = x.substring(0, 4) + "." + x.substring(4, x.length()); 

正如在评论中提到的,一个StringBuilder可能是一个更快的实现,然后使用一个StringBuffer 。 正如在Java文档中提到的:

这个类提供了一个与StringBuffer兼容的API,但是不保证同步。 这个类被devise为在单个线程正在使用string缓冲区的地方(如通常情况下)用作StringBuffer的一个直接replace。 在可能的情况下,build议将此类优先用于StringBuffer,因为在大多数实现中它将更快。

用法:

 String str = Integer.toString(j); str = new StringBuilder(str).insert(str.length()-2, ".").toString(); 

或者,如果您需要同步,请使用类似用法的StringBuffer :

 String str = Integer.toString(j); str = new StringBuffer(str).insert(str.length()-2, ".").toString(); 
 int your_integer = 123450; String s = String.format("%6.2f", your_integer / 100.0); System.out.println(s); 

你可以使用

 System.out.printf("%4.2f%n", ((float)12345)/100)); 

根据评论,12345 / 100.0会更好,如使用双重而不是浮动。

如果你正在使用一个浮点数很高的系统(例如没有FPU)或不允许(例如在会计中)使用类似这样的东西:

  for (int i = 1; i < 100000; i *= 2) { String s = "00" + i; System.out.println(s.substring(Math.min(2, s.length() - 2), s.length() - 2) + "." + s.substring(s.length() - 2)); } 

否则DecimalFormat是更好的解决scheme。 (上面的StringBuilder变体不适用于小数字(<100)

  public static void main(String[] args) { char ch='m'; String str="Hello",k=String.valueOf(ch),b,c; System.out.println(str); int index=3; b=str.substring(0,index-1 ); c=str.substring(index-1,str.length()); str=b+k+c; } 

在大多数使用情况下,使用StringBuilder (已经回答)是一个很好的方法。 但是,如果performance很重要,这可能是一个很好的select。

 /** * Insert the 'insert' String at the index 'position' into the 'target' String. * * ```` * insertAt("AC", 0, "") -> "AC" * insertAt("AC", 1, "xxx") -> "AxxxC" * insertAt("AB", 2, "C") -> "ABC * ```` */ public static String insertAt(final String target, final int position, final String insert) { final int targetLen = target.length(); if (position < 0 || position > targetLen) { throw new IllegalArgumentException("position=" + position); } if (insert.isEmpty()) { return target; } if (position == 0) { return insert.concat(target); } else if (position == targetLen) { return target.concat(insert); } final int insertLen = insert.length(); final char[] buffer = new char[targetLen + insertLen]; target.getChars(0, position, buffer, 0); insert.getChars(0, insertLen, buffer, position); target.getChars(position, targetLen, buffer, position + insertLen); return new String(buffer); }