Formatting a double to two decimal places

前端 未结 7 596
庸人自扰
庸人自扰 2020-11-27 06:25

I have been trying to make the answer this prints out to be to two decimal places. All the math involved has to stay at that format of two decimal places. I have tried a few

7条回答
  •  感动是毒
    2020-11-27 07:01

    Well, depending on your needs you can choose any of the following. Out put is written against each method

    You can choose the one you need

    This will round

    decimal d = 2.5789m;
    Console.WriteLine(d.ToString("#.##")); // 2.58
    

    This will ensure that 2 decimal places are written.

    d = 2.5m;
    Console.WriteLine(d.ToString("F")); //2.50
    

    if you want to write commas you can use this

    d=23545789.5432m;
    Console.WriteLine(d.ToString("n2")); //23,545,789.54
    

    if you want to return the rounded of decimal value you can do this

    d = 2.578m;
    d = decimal.Round(d, 2, MidpointRounding.AwayFromZero); //2.58
    

提交回复
热议问题