Get Last 2 Decimal Places with No Rounding

☆樱花仙子☆ 提交于 2019-12-04 11:19:35

问题


In C#, I'm trying to get the last two decimal places of a double with NO rounding. I've tried everything from Math.Floor to Math.Truncate and nothing is working.

Samples of the results I'd like:

1,424.2488298 -> 1,424.24
53.5821 -> 53.58
10,209.2991 -> 10,209.29

Any ideas?


回答1:


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



回答2:


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.)




回答3:


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



回答4:


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.




回答5:


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


来源:https://stackoverflow.com/questions/9931795/get-last-2-decimal-places-with-no-rounding

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