Saltar al pie de página
.NET AYUDA

Tipos numéricos en C# (Cómo funciona para desarrolladores)

In C#, numeric types are a set of data types used to store numbers and can be divided into two main categories: integer types and floating-point types. Each category has its own unique characteristics and use cases.

Numeric types form the basis of numerous operations in C#, from financial and monetary calculations to complex algorithms. If you’re looking to master C#, you’ll need to master these value types.

Integer Data Types

Integer data types are utilized to store whole numbers and can be either signed (capable of holding both positive and negative numbers) or unsigned (capable of holding only positive numbers). Here's a breakdown of the integer types in C#:

byte

The byte is the smallest integer type. It's an unsigned type, with a default value of 0, capable of storing values from 0 to 255.

sbyte

The sbyte is a signed counterpart of the byte. It can store values from -128 to 127, with a default value of 0.

short

A short is a 16-bit signed integer. It has a larger range than the byte and sbyte, from -32,768 to 32,767, with a default value of 0.

ushort

ushort is the unsigned counterpart of the short. It can hold values from 0 to 65,535. Its default value is also 0.

int

An int type is a 32-bit signed integer type, with a range from -2,147,483,648 to 2,147,483,647. The default value of an integer variable of type int is 0.

uint

The uint, short for "unsigned integer," can hold values from 0 to 4,294,967,295. Its default value is 0.

long

Long is a 64-bit signed integer type, capable of storing values from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. The default value of a long is 0L.

ulong

The ulong, or unsigned long, can store values from 0 to 18,446,744,073,709,551,615. Its default value is 0UL.

Floating-Point Number Types

Floating-point types are used to store numbers with a decimal point. A floating-point number provides a much wider range of values than integer types, but with a trade-off in precision. Here are the floating-point types in C#:

float

A float is a 32-bit floating-point type. It can represent values from approximately 1.5 x 10^-45 to 3.4 x 10^38, with a precision of 7 digits. The default value of a floating-point variable of type float is 0.0f.

double

The double type is a 64-bit floating-point type. It can represent values from approximately 5.0 x 10^-324 to 1.7 x 10^308, with a precision of 15-16 digits. The default value of a double is 0.0d.

decimal

The decimal type is a 128-bit data type. It's often used when dealing with financial calculations that require high precision. It can represent values from approximately 1.0 x 10^-28 to 7.9 x 10^28, with a precision of 28-29 digits. The default value of a decimal type is 0.0m.

Understanding Native Sized Integer Types

Native sized integer types are special types in C# that have a size that varies depending on the platform the code is running on. These are designed to provide the most efficient use of memory for storing integer values.

IntPtr

IntPtr is a signed integer type that has the same width as a pointer. This means it's 32-bit on 32-bit platforms and 64-bit on 64-bit platforms. This is useful when dealing with pointer or memory-related tasks, and the default value of an IntPtr is 0.

UIntPtr

UIntPtr, the unsigned counterpart of IntPtr, also has the same size as a pointer. It provides the same value range as IntPtr on the same platform, but only for non-negative values. The default value of an UIntPtr is also 0.

Converting Between Integer and Floating-Point Types

Depending on the use case, it’s important to use the correct data type in your code. In many cases, you may have a value of one type and need to use it as another type.

Implicit conversions happen automatically when the value to be converted will fit into the new data type without losing any information. For example, you can implicitly convert an int to a long, as a long can store the same value as an int.

Explicit conversions, also known as casting, are required when there's a risk of data loss. For example, converting a long to an int may result in data loss if the long's value is larger than what an int can hold.

To explicitly cast a value from one type to another, you can use the casting operator ():

long myLong = 5000L;
int myInt = (int)myLong; // This is an explicit cast from long to int.
                         // Be cautious if myLong > 2,147,483,647 as it may cause data loss.
long myLong = 5000L;
int myInt = (int)myLong; // This is an explicit cast from long to int.
                         // Be cautious if myLong > 2,147,483,647 as it may cause data loss.
Dim myLong As Long = 5000L
Dim myInt As Integer = CInt(myLong) ' This is an explicit cast from long to int.
						 ' Be cautious if myLong > 2,147,483,647 as it may cause data loss.
$vbLabelText   $csharpLabel

Be careful when casting, as it can lead to unexpected results if the value is outside the range of the target type.

Applying Numeric Types Using IronPDF

IronPDF is a lightweight .NET PDF library designed specifically with web developers in mind. It makes reading, writing, and manipulating PDF files a breeze, able to convert all kinds of file types into PDF content, and you can use it in your .NET projects for both desktop and web. The best part - it’s free to try out in a development environment.

Let’s take a look at implementing types in C# using IronPDF.

Positioning and Sizing Elements

In this example, we’ll tweak the position and size of elements on a page. In IronPDF, coordinates are defined using a floating-point type.

using IronPdf;

var htmlToPdf = new ChromePdfRenderer();
htmlToPdf.RenderingOptions.MarginTop = 50;    // Set top margin in points.
htmlToPdf.RenderingOptions.MarginBottom = 50; // Set bottom margin in points.

var document = htmlToPdf.RenderHtmlAsPdf("<h1>Numeric Types in C# with IronPDF</h1>");
document.SaveAs("C:\\numericTypes.pdf");       // Save the generated PDF to the specified path.
using IronPdf;

var htmlToPdf = new ChromePdfRenderer();
htmlToPdf.RenderingOptions.MarginTop = 50;    // Set top margin in points.
htmlToPdf.RenderingOptions.MarginBottom = 50; // Set bottom margin in points.

var document = htmlToPdf.RenderHtmlAsPdf("<h1>Numeric Types in C# with IronPDF</h1>");
document.SaveAs("C:\\numericTypes.pdf");       // Save the generated PDF to the specified path.
Imports IronPdf

Private htmlToPdf = New ChromePdfRenderer()
htmlToPdf.RenderingOptions.MarginTop = 50 ' Set top margin in points.
htmlToPdf.RenderingOptions.MarginBottom = 50 ' Set bottom margin in points.

Dim document = htmlToPdf.RenderHtmlAsPdf("<h1>Numeric Types in C# with IronPDF</h1>")
document.SaveAs("C:\numericTypes.pdf") ' Save the generated PDF to the specified path.
$vbLabelText   $csharpLabel

Output PDF File

Understanding C# Numeric Types, Image #1

Conclusion

From basic calculations to customizing the layout of a generated PDF, number types are an important part of effective and efficient C# programming. They serve as the building blocks for data manipulation, algorithm design, and the creation of high-quality PDF documents.

Want to get your hands on IronPDF? You can start with our 30-day free trial. It’s also completely free to use for development purposes so you can really get to see what it’s made of. And if you like what you see, IronPDF starts as low as liteLicense. For even bigger savings, check out the Iron Suite where you can get all nine Iron Software tools for the price of two. Happy coding!

Understanding C# Numeric Types, Image #2

Preguntas Frecuentes

¿Cómo puedo convertir contenido HTML en un PDF usando C#?

Puedes convertir contenido HTML en un PDF en C# utilizando el método RenderHtmlAsPdf de IronPDF, que te permite transformar cadenas HTML directamente en documentos PDF. Además, puedes usar RenderHtmlFileAsPdf para convertir archivos HTML.

¿Cuáles son las principales diferencias entre los tipos enteros y de punto flotante en C#?

En C#, los tipos enteros se usan para números enteros e incluyen tipos como byte, int y long. Los tipos de punto flotante, como float y double, manejan números con puntos decimales, ofreciendo un rango más amplio pero menos precisión.

¿Por qué usaría un tipo decimal en lugar de un double en C#?

El tipo decimal proporciona mayor precisión, lo que lo hace ideal para cálculos financieros donde la representación decimal exacta es crucial. Puede representar valores con una precisión de 28-29 dígitos, en comparación con los 15-16 dígitos de un double.

¿Cómo benefician los tipos enteros de tamaño nativo a los desarrolladores de C#?

Los tipos enteros de tamaño nativo como IntPtr y UIntPtr ajustan su tamaño según la plataforma, ofreciendo eficiencia de memoria para tareas como el manejo de direcciones de memoria y punteros en escenarios específicos de la plataforma.

¿Qué papel juegan los tipos numéricos en la generación de PDF con .NET?

Los tipos numéricos en la generación de PDF con .NET son esenciales para definir el diseño de los elementos PDF. Por ejemplo, los números de punto flotante pueden especificar el tamaño y la posición precisa de texto e imágenes en una página PDF usando IronPDF.

¿Qué son las conversiones implícitas y explícitas en C#?

Las conversiones implícitas en C# ocurren cuando el tipo de destino puede almacenar el valor de origen sin pérdida de datos. Las conversiones explícitas, o de casting, requieren intervención manual, a menudo usando un operador de conversión, debido a la potencial pérdida de datos.

¿Cómo puedo evaluar una biblioteca PDF de .NET para mi proyecto?

Puedes evaluar una biblioteca PDF de .NET como IronPDF aprovechando su prueba gratuita de 30 días. Esto te permite explorar sus características durante el desarrollo antes de decidirte por la compra de una licencia.

Curtis Chau
Escritor Técnico

Curtis Chau tiene una licenciatura en Ciencias de la Computación (Carleton University) y se especializa en el desarrollo front-end con experiencia en Node.js, TypeScript, JavaScript y React. Apasionado por crear interfaces de usuario intuitivas y estéticamente agradables, disfruta trabajando con frameworks modernos y creando manuales bien ...

Leer más