0

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

Buh Buh
  • 7,443
  • 1
  • 34
  • 61
murli
  • 13
  • 1
  • 7

3 Answers3

2

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}");
Johan Donne
  • 3,104
  • 14
  • 21
0

You can use .ToString("0.00") whenever you want to display it

Console.WriteLine(finalValue.ToString("0.00"));
AmirJabari
  • 406
  • 3
  • 9
0

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)

Bilal Bin Zia
  • 596
  • 3
  • 12