I am using Math.Round() Method to round off a double value. But I want to keep the trailing zeroes. For Example:
double x = 0.4701589;
Math.Round(x*100,2);
This returns 4.7 however the desired output is 4.70
I am using Math.Round() Method to round off a double value. But I want to keep the trailing zeroes. For Example:
double x = 0.4701589;
Math.Round(x*100,2);
This returns 4.7 however the desired output is 4.70
The problem is not with the rounding but with the formatting of your result. You can specify it needs to be printed with 2 decimals:
double x = 0.04701589;
double y = Math.Round(x*100, 2);
Console.WriteLine($"default formatting: {y}");
Console.WriteLine($"specify 2 digits: {y:f2}");
You can use .ToString("0.00") whenever you want to display it
Console.WriteLine(finalValue.ToString("0.00"));
Try this
int numDigitsAfterPoint = 5;
double num = 1.25d;
string result = num.ToString("F" + numDigitsAfterPoint);
Keep in mind that, ToString uses the MidpointRounding.AwayFromZero instead of the MidpointRounding.ToEven (also called Banker's Rounding). As an example:
var x1 = 1.25.ToString("F1");
var x2 = 1.35.ToString("F1");
var x3 = Math.Round(1.25, 1).ToString();
var x4 = Math.Round(1.35, 1).ToString();
These will produce different result (because Math.Round normally uses MidpointRounding.ToEven)