Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Represent Int64 as a String in C#
The Int64 data type in C# represents a 64-bit signed integer that can hold values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Converting an Int64 to a string is a common operation that can be accomplished using several methods, with ToString() being the most straightforward approach.
Syntax
The basic syntax for converting an Int64 to string using ToString() method −
long variable = value; string result = variable.ToString();
You can also use format specifiers with ToString() −
string result = variable.ToString("format");
Using ToString() Method
The simplest way to convert an Int64 to string is using the ToString() method without any parameters −
using System;
class Demo {
static void Main() {
long val = 8766776;
string result = val.ToString();
Console.WriteLine("Long converted to string = " + result);
Console.WriteLine("Type of result: " + result.GetType());
}
}
The output of the above code is −
Long converted to string = 8766776 Type of result: System.String
Using Format Specifiers
You can format the Int64 value while converting it to string using various format specifiers −
using System;
class Demo {
static void Main() {
long val = 1234567890;
Console.WriteLine("Default: " + val.ToString());
Console.WriteLine("With commas: " + val.ToString("N0"));
Console.WriteLine("Currency: " + val.ToString("C"));
Console.WriteLine("Hexadecimal: " + val.ToString("X"));
Console.WriteLine("Fixed decimal: " + val.ToString("F2"));
}
}
The output of the above code is −
Default: 1234567890 With commas: 1,234,567,890 Currency: $1,234,567,890.00 Hexadecimal: 499602D2 Fixed decimal: 1234567890.00
Using Convert.ToString() Method
Another approach is to use the Convert.ToString() method, which provides additional options like specifying the base for conversion −
using System;
class Demo {
static void Main() {
long val = 255;
Console.WriteLine("Decimal: " + Convert.ToString(val));
Console.WriteLine("Binary: " + Convert.ToString(val, 2));
Console.WriteLine("Octal: " + Convert.ToString(val, 8));
Console.WriteLine("Hexadecimal: " + Convert.ToString(val, 16));
}
}
The output of the above code is −
Decimal: 255 Binary: 11111111 Octal: 377 Hexadecimal: ff
Comparison of Methods
| Method | Use Case | Example |
|---|---|---|
| ToString() | Basic conversion, format specifiers | val.ToString("N0") |
| Convert.ToString() | Base conversion (binary, octal, hex) | Convert.ToString(val, 2) |
| String interpolation | Embedding in larger strings | $"Value: {val}" |
Conclusion
Converting Int64 to string in C# is straightforward using ToString() for basic conversion and formatting, or Convert.ToString() for base conversions. Choose the method based on your specific formatting or base conversion requirements.
