Have decimal amount, want to trim to 2 decimal places if present

╄→尐↘猪︶ㄣ 提交于 2020-01-21 06:41:01

问题


Have decimal amount, want to trim to 2 decimal places if present


回答1:


Have you tried using value = Decimal.Round(value, 2)?

For example:

using System;

class Test
{    
    static void Main()
    {
        decimal d = 1234.5678m;
        Console.WriteLine("Before: {0}", d); // Prints 1234.5678
        d = decimal.Round(d, 2);
        Console.WriteLine("After: {0}", d); // Prints 1234.57
    }
}

Note that this is rounding rather than just trimming (so here it's rounded up)... what exactly do you need? Chances that the Decimal struct supports whatever you need to do. Consult MSDN for more options.




回答2:


decimal.Truncate(myDecimal * 100) / 100

This would cut away everything following the first two decimal places. For rounding see Jon's answer.




回答3:


If its just for display purposes, you can use:

Console.Out.WriteLine("Number is: {0:F2}", myDecimalNumber);



回答4:


This should work (EDIT: Fixed to remove rounding):

((Int32)(value * Math.Pow(10, decimalPlaces))) / (Math.Pow(10D, decimalPlaces));



回答5:


I use this: Math.Round(MyDecimalValue,2);



来源:https://stackoverflow.com/questions/4695053/have-decimal-amount-want-to-trim-to-2-decimal-places-if-present

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!