Digit Separators in C#

Digit Separators in C# with examples

In this article, I am going to discuss the Digit Separators in C# with some examples. Please read our previous article before proceeding to this article where we discussed the Pattern Matching in C# with examples.

In reality, it’s very difficult to read a very large number. To overcome this problem, C# 7 comes with a new feature called digit separators “_”. Now, it is possible to use one or more Underscore (_) character as digit separators. Sometimes, it is required when we are going to represent a very big number. 

Let’s understand Digit Separators with an example.
class Program
{
    static void Main()
    {
        // Both are equivalent.
        var bigNumber = 123456789012345678;
        var bigNumberSplit = 123_456_789_012_345_678;

        Console.WriteLine("bigNumber : {0}, bigNumberSplit : {1}", bigNumber, bigNumberSplit);

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
When we run the application it gives us the following output.

Digit Separators in C# 7

If you observe in the code, then you feel a little difficult to read the first number as it is a very big number. But, you can easily read the second number because of the thousands separator. 

The separators make no difference in the value as we can see in the above output. You can place them wherever you like in the number, and in any quantity. And in case you’re wondering, you’re not restricted to using them with integers only; they also work with the other numeric types as well.

It is also not mandatory to use a single underscore as a separator even though you can also use multiple separators.

Let’s see the above two points with an example.

Modify the main method as shown below

class Program
{
    static void Main()
    {
        var myData1 = 1__2________3___4____5_____6;
        var myData2 = 1__2___3___4____5_____6.79;
        Console.WriteLine("bigNumber : {0}, bigNumberSplit : {1}", myData1, myData2);

        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}

Now when we run the application, it gives us the output as expected as shown in the below image.

Digit Separators in C#

In the next article, I am going to discuss the Tuples in C# with some real-time examples.

SUMMARY

In this article, I try to explain Digit Separators step by step with some simple examples. I hope you understood the use and need of C# Digit Separators.

Leave a Reply

Your email address will not be published. Required fields are marked *