/*Converting a number to string can be done very eaisly in java .We can do in many ways .
1. We can use toString() method of Integer , Byte , Long class . The Integer and Long classes also provide the methods like toBinaryString(), toHexString(), toOctalString();
2. String.valueOf can be used to convert number to string.
3. java.text.DecimalFormat is used to parse and format numbers in any locale
4. Simple Concatenation (+) : Any integer concatenated with string is converted to string . */
import java.text.DecimalFormat;
import java.io.*;
public class NumberToStr {
public static void main(String[] args) {
Example1();
Example2();
}
// Example 1:
private static void Example1()
{
System.out.println("Example 1 ");
int number = 1932;
System.out.println ("Given Number is : " + number); // using concatenation
System.out.println(" Number to String by toString(): " + Integer.toString(number)); // using toString of Integer
System.out.println(" Number to String by valueOf(): " + String.valueOf(number)); // using valueOf of String
System.out.println(" Number to Binary : " + Integer.toBinaryString(number));
System.out.println(" Number to Hexadecimal : " + Integer.toHexString(number));
System.out.println(" Number to Octal : " + Integer.toOctalString(number));
}
// Example 2:
private static void Example2()
{
System.out.println("Example 1 ");
DecimalFormat df= new DecimalFormat("##,###.##");
int number = 400;
String str1="" + number ; //using concatenation
String str2 = "Number is "+number; //using concatenation
double decimal = 65132.39 ;
String numInFormat = df.format(decimal);
System.out.println("String1 = " +str1);
System.out.println("String2 = " +str2);
System.out.println("Number in Format = " +numInFormat);
}
}
Output :
-----------
D:\as2\JF1>java NumberToStr
Example 1
Given Number is : 1932
Number to String by toString(): 1932
Number to String by valueOf(): 1932
Number to Binary : 11110001100
Number to Hexadecimal : 78c
Number to Octal : 3614
Example 1
String1 = 400
String2 = Number is 400
Number in Format = 65,132.39
0 comments:
Post a Comment