Convert a Number to a String

From Progzoo
Jump to: navigation, search

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

Number to String by adding an empty string

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.

[Font] [Default] [Show] [Resize] [History] [Profile]

Boxing the number

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

[Font] [Default] [Show] [Resize] [History] [Profile]

Creating a string

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.

[Font] [Default] [Show] [Resize] [History] [Profile]