C#:Convert a Number to a String

From Progzoo
Jump to navigation Jump to 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

All objects support the ToString() method - this will convert almost anything into a string.

[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 {0} spaces where the first parameter is included.

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. In this example there are 8 spaces and 2 decimal places {0,8:n2}

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