Today we’re going to look at a short post, but I think it’s important, since many people are unaware of this feature in C#, and not only that, we’re also going to see a library that makes it much easier to represent large numbers.
1 - Integer types
Everything we’re going to see here refers to numeric integer types, meaning positive and negative numbers without decimals, in C# language terms. We have sbyte
, byte
, short
, ushort
, int
, uint
, long
, ulong
, nint
, nuint
.
The difference between long
and ulong
is that long is signed (can be positive or negative) and ulong
is not, which means that the number you can represent is “larger,” although it will always be “positive”. In the signed version 32 bits
are positive and 32 bits negative, while the unsigned version is 64 bits
positive.
1.1 - Literals
Within the integer types, we also have different forms, such as decimals, which we just saw, hexadecimal values which have a 0X
prefix, or binary values with a 0B
prefix.
For example, if we represent the value 2022, it would look like this:
var hex = 0X7E6
var binary = 0b11111100110
2 - Assigning values in our code
The main reason for this post is the following info. When we represent a number like 2022, it’s easy to read in code, but what happens if our number is larger? For example, 43209412016
. That number, at a glance, is impossible to tell what it is.
C# provides a feature that allows us to represent numbers in a more readable way, which is adding an underscore (_
) between digits. So the next number would look like this:
long valor = 43_209_412_016
2.1 - Numerize library
But for me, this is not enough. I’ve created a library that lets us indicate that same number but in English, which makes it much easier to read.
The library in question is Numerize, and I invite you to give it a star ⭐. Of course, it’s also on Nuget.
With the library, we can write the number in English without worrying about underscores or not being able to recognize the number at a glance.
For example, with the previous number, we can do the following:
long value = Numerize.Fourty.Three().Billion()
.Two().Hundred().Nine().Milion()
.Four().Hundred().Twelve().Thousand()
.Sixteen();
And with the use of implicit operators it also converts the number to text:
Numerize numerize = new Numerize();
string result = numerize.Fourty().Three().Billion()
.Two().Hundred().Nine().Milion()
.Four().Hundred().Twelve().Thousand()
.Sixteen();
And it gives us the following (in English): forty three billion two hundred nine million four hundred twelve thousand sixteen
.
Which is much more friendly.
If there is any problem you can add a comment bellow or contact me in the website's contact form