Get Last 2 Decimal Places with No Rounding

狂风中的少年 提交于 2019-12-03 06:56:14

Well, mathematically it's simple:

var f = 1.1234;
f = Math.Truncate(f * 100) / 100;  // f == 1.12

Move the decimal two places to the right, cast to an int to truncate, shift it back to the left two places. There may be ways in the framework to do it too, but I can't look right now. You could generalize it:

double Truncate(double value, int places)
{
    // not sure if you care to handle negative numbers...       
    var f = Math.Pow( 10, places );
    return Math.Truncate( value * f ) / f;
}

My advice: stop using double in the first place. If you need decimal rounding then odds are good you should be using decimal. What is your application?

If you do have a double, you can do it like this:

double r = whatever;
decimal d = (decimal)r;
decimal truncated = decimal.Truncate(d * 100m) / 100m;

Note that this technique will fail if the absolute value of the double is larger than 792281625142643375935439504, because the multiplication by 100 will fail. If you need to handle values that large then you'll need to use special techniques. (Of course, by the time a double is that large, you are well beyond its ability to represent values with two digits after the decimal place anyway.)

 double d = Math.Truncate(d * 100) / 100;

A general solution:

    public static double SignificantTruncate(double num, int significantDigits)
    {
        double y = Math.Pow(10, significantDigits);
        return Math.Truncate(num * y) / y;
    }

Then

    double x = 5.3456;
    x = SignificantTruncate(x,2);

Will produce the desired result x=5.34.

Math.Round(NumberToRound - (double)0.005,2)

i.e

Math.Round(53.5821 - (double)0.005,2) // 53.58
Math.Round(53.5899 - (double)0.005,2) // 53.58
Math.Round(53.5800 - (double)0.005,2) // 53.58
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!