How to round a decimal up?

眉间皱痕 提交于 2019-12-23 06:56:48

问题


Given a decimal '96.154', how can I ensure that it is always rounded up to 96.16 (as opposed to normal rounding to 2 decimals which would give 96.15).


回答1:


Kind of hacky but a very intuitive way to do so:

var val = 96.154M;

var result = Math.Ceiling(val * 100) / 100.0M;



回答2:


You can add 0.005 to the value and then round the result.




回答3:


I think your looking for the Math.Ceiling method.

You could combine this with a multiplier to specify how many decimal places to round. Like this,

public float roundUp(float number, int numDecimalPlaces)
{
    double multiplier = Math.Pow(10, numDecimalPlaces))

    return Math.ceiling(number*multiplier) / multiplier;
}



回答4:


Here is the code of a roundUp method for a value and base fraction. The base fraction you should use for your question is 0.05M. However the method can be used for other common scenario which is base fraction 0.5M; And you can apply it in interesting ways like for example using a base fraction of 0.3M. Well I hope it should answer your questions, have fun :

static decimal roundUp(decimal aValue, decimal aBaseFraction)
{
   decimal quotient = aValue / aBaseFraction;
   decimal roundedQuotient = Math.Round(quotient, 0);
   decimal roundAdjust = 0.0M;
   if (quotient > roundedQuotient)
   {
      roundAdjust = aBaseFraction;
   }
   return roundAdjust + roundedQuotient * aBaseFraction;
}



回答5:


Here is my version of a RoundUp method, In this can specific decimal

void Main()
{
    Console.WriteLine(RoundUp(2.8448M, 2));
    //RoundUp(2.8448M, 2).Dump();
}

public static decimal RoundUp(decimal numero, int numDecimales)
{
    decimal valorbase = Convert.ToDecimal(Math.Pow(10, numDecimales));
    decimal resultado = Decimal.Round(numero * 1.00000000M, numDecimales + 1, MidpointRounding.AwayFromZero) * valorbase;
    decimal valorResiduo = 10M * (resultado - Decimal.Truncate(resultado));

    if (valorResiduo < 5)
    {
        return Decimal.Round(numero * 1.00M, numDecimales, MidpointRounding.AwayFromZero);
    }
    else
    {
        var ajuste = Convert.ToDecimal(Math.Pow(10, -(numDecimales + 1)));
        numero += ajuste;
        return Decimal.Round(numero * 1.00000000M, numDecimales, MidpointRounding.AwayFromZero);
    }
}


来源:https://stackoverflow.com/questions/11794579/how-to-round-a-decimal-up

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