围捕在C#2位小数 [英] Rounding up to 2 decimal places in C#

查看:99
本文介绍了围捕在C#2位小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个十进制数可以是这样的:

I have a decimal number which can be like the following:

189.182

我想这一轮的最多的2位小数,所以输出将是以下内容:

I want to round this up to 2 decimal places, so the output would be the following:

189.19

时有内置的功能,这在数学类,或者其他什么东西?我知道天花板函数存在,但这似乎并没有做我想做的 - 它会舍入到最近INT,所以就在这种情况下,189

Is there built in functionality for this in the Math class, or something else? I know the ceiling function exists but this doesn't seem to do what I want - it'll round to the nearest int, so just '189' in this case.

推荐答案

乘以100,呼叫天花板,除以100做什么,我想你问的

Multiply by 100, call ceiling, divide by 100 does what I think you are asking for

public static double RoundUp(double input, int places)
{
    double multiplier = Math.Pow(10, Convert.ToDouble(places));
    return Math.Ceiling(input * multiplier) / multiplier;
}

使用看起来像:

RoundUp(189.182, 2);

这的工作原理是将小数点右边2位(所以它是对过去8的右侧)然后执行所述天花板的操作,然后将小数点回到其原来的位置。

This works by shifting the decimal point right 2 places (so it is to the right of the last 8) then performing the ceiling operation, then shifting the decimal point back to its original position.

这篇关于围捕在C#2位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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