Menu
Topics Index
...
`

Converting Numbers to String - Java Example Program


Converting Numbers to String
class NumberstoStringTest
{
    public static void main(String arg[])
    {
        int i = 32;
        String s1 = "" + i; // LINE A
        System.out.println("s1 = " + s1);
        
        double d = 876.54;
        String s2 = String.valueOf(d); // LINE B
        System.out.println("s2 = " + s2);
        
        float f = 156.8f;
        String s3 = Float.toString(f); // LINE C
        System.out.println("s3 = " + s3);
        
        String s4 = "" + i + d; // LINE D
        
        System.out.println("s4 = " + s4);
        int n = s4.indexOf('.');
        System.out.println(n + " Digits before decimal point of s4 string.");
        System.out.println(s4.length() - n - 1
                + " Digits after decimal point of s4 string.");    
    }
}
OUTPUT

s1 = 32
s2 = 876.54
s3 = 156.8
s4 = 32876.54
5 Digits before decimal point of s4 string.
2 Digits after decimal point of s4 string.

DESCRIPTION

In this program, at LINE A, int is converted into String by concatenating with empty string,
At LINE B double is converted into String using valueOf method,
At LINE C float is converted into String using toString method and finally at LINE D, we are concatenating empty String, integer and double.
We are counting number of digits before and after the decimal point, in the resultant String.

THINGS TO TRY
  • Apply valueOf method to different data types as String.valueOf(datatype).
  • Apply toString method to all the data types as Integer.toString(integer_Datatype), Double.toString(double_datatype) etc.,
  • Try to perform operations on the resultant strings.

© meritcampus 2019

All Rights Reserved.

Open In App