How to round a decimal for output?

心不动则不痛 提交于 2019-11-27 03:49:59

问题


Using C#, I want to format a decimal to only display two decimal places and then I will take that decimal and subtract it to another decimal. I would like to be able to do this without having to turn it into a string first to format and then convert it back to a decimal. I'm sorry I forget to specify this but I don't want to round, I just want to chop off the last decimal point. Is there a way to do this?


回答1:


If you don't want to round the decimal, you can use Decimal.Truncate. Unfortunately, it can only truncate ALL of the decimals. To solve this, you could multiply by 100, truncate and divide by 100, like this:

decimal d = ...;
d = Decimal.Truncate(d * 100) / 100;

And you could create an extension method if you are doing it enough times

public static class DecimalExtensions
{
  public static decimal TruncateDecimal(this decimal @this, int places)
  {
    int multipler = (int)Math.Pow(10, places);
    return Decimal.Truncate(@this * multipler) / multipler;
  }
}



回答2:


You can use: Math.Round(number,2); to round a number to two decimal places.

See this specific overload of Math.Round for examples.




回答3:


Math.Round Method (Decimal, Int32)




回答4:


You don't want to format it then, but to round it. Try the Math.Round function.




回答5:


Take a look at Math.Round



来源:https://stackoverflow.com/questions/697977/how-to-round-a-decimal-for-output

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