Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (920 points)

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

1 Answer

0 votes
by (13.2k points)
  1. substring ()

To insert a character in a string at a certain position you can use substring method of java class, whose syntax is -

public String substring(int startIndex, int endIndex)

 This method returns a string starting from startIndex ( included ) to the endIndex (excluded) .

int j= 123456 

String str = Integer.toString(j);

str = str.substring(0, str.length()-2) + "." +str.substring(str.length()-2);

2. String Buffer 

It has similar usage.

String str = Integer.toString(j);

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

3. String Builder

It has faster implementation than String Buffer.

String str = Integer.toString(j);

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

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...