Get Last 2 Decimal Places with No Rounding

前端 未结 5 1980
青春惊慌失措
青春惊慌失措 2021-02-06 04:05

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 nothin

5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 04:55

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

提交回复
热议问题