How to insert a character in a string at a certain position?

457,294

Solution 1

int j = 123456;
String x = Integer.toString(j);
x = x.substring(0, 4) + "." + x.substring(4, x.length());

Solution 2

As mentioned in comments, a StringBuilder is probably a faster implementation than using a StringBuffer. As mentioned in the Java docs:

This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Usage :

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

Or if you need synchronization use the StringBuffer with similar usage :

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

Solution 3

int yourInteger = 123450;
String s = String.format("%6.2f", yourInteger / 100.0);
System.out.println(s);

Solution 4

Using ApacheCommons3 StringUtils, you could also do

int j = 123456;
String s = Integer.toString(j);
int pos = s.length()-2;

s = StringUtils.overlay(s,".", pos, pos);

it's basically substring concatenation but shorter if you don't mind using libraries, or already depending on StringUtils

Solution 5

In most use-cases, using a StringBuilder (as already answered) is a good way to do this. However, if performance matters, this may be a good alternative.

/**
 * 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);
}
Share:
457,294

Related videos on Youtube

daverocks
Author by

daverocks

Updated on March 15, 2022

Comments

  • daverocks
    daverocks about 2 years

    I'm getting in an int with a 6 digit value. I want to display it as a String with a decimal point (.) at 2 digits from the end of int. I wanted to use a float but was suggested to use String for a better display output (instead of 1234.5 will be 1234.50). Therefore, I need a function that will take an int as parameter and return the properly formatted String with a decimal point 2 digits from the end.

    Say:

    int j= 123456 
    Integer.toString(j); 
    
    //processing...
    
    //output : 1234.56
    
    • user881703
      user881703 over 5 years
      String str = Integer.toString(j); //integer or string with white spaces<br/> str = new StringBuffer(str.trim()).insert(str.length()-2, ".").toString();
  • Joseph Ottinger
    Joseph Ottinger about 13 years
    In the case of accounting, you'd be better off with BigDecimal.
  • Vishy
    Vishy about 13 years
    double might be a better choice. float is only accurate to 6 digits.
  • Joseph Ottinger
    Joseph Ottinger about 13 years
    Yeah, another example someone responded with was to use 12345/100.0, which is smarter (although it ends up with the same result.)
  • rurouni
    rurouni about 13 years
    @Joseph: You are right. I'm not in accounting and I mostly use ints as a fixedpoint representation for performance reasons (in embedded java), so BigDecimal is not my choice ;-)
  • rurouni
    rurouni almost 13 years
    Nitpicking: I think this wont't give the right result, because 12345/100 = 123 in integer and is only cast to 123.00 afterwards. ((float)12345/100) would work.
  • Joseph Ottinger
    Joseph Ottinger almost 13 years
    Heh, good point - I wasn't taking the precedence into account, mostly because the very first time he ran it it'd give him the truncated result. Will fix the post (which used to say 12345/100, then cast the result, instead of widening the value first.)
  • wheresmycookie
    wheresmycookie almost 11 years
    Strings are immutable. While this works, using something like StringBuilder is morally correct, not to mention will make your code faster.
  • NobleUplift
    NobleUplift almost 11 years
    Forget StringBuilder. With formatting such as this, String.format is the best option available.
  • Remi Morin
    Remi Morin over 10 years
    There is no loop, it's a simple concatenation case and compiler should optimize it using a string builder, for readability I prefer to use the + operator, there is no need in this case to use StringBuilder explicitly. Using "StringBuilder" solution because it's faster don't respect optimization rules. Code for readability. Optimize after profiling and only where it is require. en.wikipedia.org/wiki/Program_optimization#Quotes
  • sotrh
    sotrh over 9 years
    This solution works for any string >= 4 characters: the string "111" gave me ".111", and anything less than that results in a java.lang.StringIndexOutOfBoundsException (attempting to access a reference that doesn't exist).
  • sotrh
    sotrh over 9 years
    I would suggest using java.math.BigDecimal as using double can cause rounding error. If speed is more valuable than precision double is better.
  • crazyGuy
    crazyGuy over 8 years
    You do not need x.length() on the second substring call.
  • Tim Diekmann
    Tim Diekmann almost 6 years
    Welcome to Stack Overflow! Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others. Thanks for improving the answer's reference value and making it more understandable!
  • Vishy
    Vishy almost 6 years
    Please don't use StringBuffer as it was replaced by StringBuilder in 2004.
  • Teodor Marinescu
    Teodor Marinescu over 5 years
    This solution will fail when the number is a different number of digits. For 12345 it will output 1234.5 and for 1234567 it will be 1234.567. If you always want the last 2 digits to be after the decimal point, the make sure the number has at least 3 digits and then do x = x.substring(0, x.length()-2) + "." + x.substring(x.length()-2);
  • kkurian
    kkurian over 4 years
    To whoever downvoted this: Re-read what the OP described in detail. This provides an exact answer to the problem: No floating point math. Puts the decimal point in the right place. To wit, stackoverflow.com/a/5884413/972128 provides a similar answer but uses floating point (not desired), and has 17 upvotes at this time.