I am diving 2 decimal number and want value upto 5 precision. below is my code.
decimal postiveTotal = 3,totalLenght = 6;
decimal postiveFractionResult = postiveTotal / totalLenght;
I m expecting 0.50000 but I am getting 0.5
I am diving 2 decimal number and want value upto 5 precision. below is my code.
decimal postiveTotal = 3,totalLenght = 6;
decimal postiveFractionResult = postiveTotal / totalLenght;
I m expecting 0.50000 but I am getting 0.5
C# number display type like decimal will always strip the appended 0 - there is no difference between 0.5 and 0.50.
If you want to have the output correctly formatted you need to use a string format identifier:
Custom number format identifier:
Console.WriteLine($"{postiveFractionResult:0.00000}");
Standard number format identifier:
Console.WriteLine($"{postiveFractionResult:F5}");
Assignment to variables:
// using string interpolation
string result = $"{postiveFractionResult:0.00000}";
// using string.format explicite
string result = string.Format("{0:0.00000}", postiveFractionResult);
You can find more information on string format here.
EDIT
As noted by Daisy Shipton there is a difference when declaring a variable either by 0.5M or 0.50M. A little test with the different declaration shows that the additional defined 0 is also preserved through calculation:
var result = 1.25m * 0.5m; // 6.25M
var result1 = 1.250m * 0.5m; // 0.6250M
var result2 = 1.250m * 0.50000m; // 0.62500000M
var result3 = 1.25000m * 0.5m; // 0.625000M
var result4 = 1.25000m * 0.50000m; // 0.6250000000M
Please see also the following so post which has an explanation about this behavior. Sadly the links are broken and I could not find the correct ECMA link due to the website being currently offline.