Get Last 2 Decimal Places with No Rounding

前端 未结 5 1981
青春惊慌失措
青春惊慌失措 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 05:03

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

提交回复
热议问题