Currently I have a problem that seems very particular to me, it turns out that when I make a code declaring a variable of type "double" or "int" in Visual Studio, and perform a simple division on it, such as:
int nEntero = 5;
Double decimal = nEntero /100;
Console.WriteLine(decimal);
// La idea es que imprima 0.05 como resultado
// Pero en cambio me muestra solo el numero entero, osea 0.
It turns out that when using it to get percentages, for example, everything gives 0, because every number multiplied by 0 is equal to 0.
I show you some test on the output that Visual Studio does.
I appreciate if you can help me to solve it. Stay tuned.
ISSUE
It so happens that the literal value 100 when parsed by the C# compiler (and by many other languages) is assumed to be an integer type. Therefore the division represented by:
will also be of type integer , so the decimals are discarded and the value corresponding to the integer part is returned.
Then, the type that you apply to the variable is effectively performed but on the value of the result of the division, which no longer has the decimals, producing as output simply a
0.0
(whennEntero
it is less than100
)On the other hand, the use of the reserved word
decimal
for a variable is not allowed, I don't understand how your program even compiles.SOLUTION
One way to fix it is to do a conversion of the variable type before doing the split, as the other answer suggests , eg:
Or even:
However, we can avoid making the cast explicit by writing the value 100 in such a way that it is recognized as a floating point type. To do this we must accompany it with a decimal point followed by a zero or 2 zeros (or any value for the decimal part that is required). For example:
Or maybe:
In this way, C# will cast (implicitly) the integer type, represented by
nEntero
, to floating point, and then proceed to perform the floating point division.Depending on the needs of your application, you can set the expected level of precision using the
float
,decimal
ordouble
. For example:Lastly, a note :
In the case of your question, no such explicit conversion is needed because a type
integer
can be implicitly converted todecimal
.I hope this helps you solve the problem.
Try to parse the nInteger to float...
I Hope I've been helpful