如何轮输出小数点? [英] How to round a decimal for output?

查看:118
本文介绍了如何轮输出小数点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#,我想格式化小数只显示小数点后两位,然后我会采取十进制,并减去另一个小数。我希望能够做到这一点,而不必把它变成一个字符串先格式化,然后再转换回小数。对不起,我忘了指定这个,但我不想舍,我只是想砍掉最后一个小数点。有没有办法做到这一点?

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?

推荐答案

如果您不想四舍五入小数,你可以使用Decimal.Truncate。不幸的是,它只能拦截所有的小数。为了解决这个问题,你可以乘以100,截断和除以100,这样的:

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;
  }
}

这篇关于如何轮输出小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆