Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 979
daverocks Avatar asked May 04 '11 13:05

daverocks


People also ask

How do you get the character at a specific position of a string?

charAt(int position) method of String Class can be used to get the character at specific position in a String. Return type of charAt(int position) is char. Index or position is counted from 0 to length-1 characters.

How do you add a character to a specific position in Java?

Syntax: str. insert(int position, char x); str. insert(int position, boolean x); str.


2 Answers

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(); 
like image 50
blo0p3r Avatar answered Sep 23 '22 10:09

blo0p3r


int j = 123456; String x = Integer.toString(j); x = x.substring(0, 4) + "." + x.substring(4, x.length()); 
like image 31
Mike Thomsen Avatar answered Sep 23 '22 10:09

Mike Thomsen