Zoo tutorials: [ SQL | Linux | XML ]
ProgZoo: [ Java | C# | VB | C++ | Perl ]
Log in

A Gentle Introduction to
Java Programming

Converting a number to a String

 

Data types

Converting a number to a String

The easy way to do this is to concatenate an empty string.

The complicated way to do this is to box the number and use toString

The powerful way to do this is to use String.format method

1. [ Java ] Number to String by adding an empty string


Big

When used with two strings the + operator just jams the two strings together. If one is a string and another a number then the number is turned into a string first. If both are numbers then + does add.

2. [ Java ] Boxing the number


Big

We can make the number into an object. All objects support the toString() method that does the job.

3. [ Java ] Creating a string


Big

The static method String.format takes a format string and a list of numbers (or pretty much anything). The format string includes %d spaces where the integers should go or %f places for the floating point numbers.

We can specify the total number of characters to use (the number is right justified in this space). We can specify the number of decimal places to use.