I tried this:
var b = 100 / 95;
and b is declared as an integer. But I would like to have a number with a decimal point.
How can I do this in C#?
I tried this:
var b = 100 / 95;
and b is declared as an integer. But I would like to have a number with a decimal point.
How can I do this in C#?
With two integer operands, the C# overload resolution picks a version of the division operator that does integer division.
To make C# choose real division, you need to change the type of at least one of the operands into decimal
, float
, or double
.
You can achieve this by casting, in the general case. In your specific case, you can also just change the literals involved:
var b = 100m / 95; // decimal
var b = 100f / 95; // float
var b = 100.0 / 95; // double
Use decimal
if these are exact, human-made quantities (e.g. money). Use float
or double
if you are dealing with approximate, physical quantities (e.g. irrational numbers, physical constants, etc).
You are doing an integer division which will ignore the fractional part of the division as it can not be stored in an int
.
If you cast your variables to decimal
s you can store the fractional part of the division:
decimal b = (decimal)100 / (decimal)95;