Casting numbers to String
- In this lesson we’ll explore two different approaches of casting numbers into String. (But there are few more in the real world.)
Using .toString
- One approach of casting int to String is by using “<Numeric data type>.toString()”.
- We can cast integers and floating point values using this method.
- In this method, we need to specify the numeric data type as Integer, Double, Float, Byte or Long before .toString().
- The following example explains that.
// Int to String
str1 = Integer.toString(num);
// Double to String
str2 = Double.toString(dbl);
// Float to String
str3 = Float.toString(flt);
// Byte to String
str4 = Byte.toString(byt);
// Long to String
str5 = Long.toString(lng);
Run this
Using String.valueOf
- Another approach is by using “String.valueOf()” to cast a number into String.
- Using “String.valueOf()”, we can cast just any numeric data type into a String.
- The following example explains that.
- The ‘num’ variable can be either integer, float, double, byte or long.
str = String.valueOf(num);
- Both of these approaches will effectively cast an integer value to String.
Run this
An integer value can be assigned to a String variable using “String.valueOf()”.