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
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.
Syntax: str. insert(int position, char x); str. insert(int position, boolean x); str.
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();
int j = 123456; String x = Integer.toString(j); x = x.substring(0, 4) + "." + x.substring(4, x.length());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With