Get Last 2 Decimal Places with No Rounding

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

    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.

提交回复
热议问题