Truncate number of digit of double value in C#

后端 未结 12 783
死守一世寂寞
死守一世寂寞 2020-12-30 04:35

How can i truncate the leading digit of double value in C#,I have tried Math.Round(doublevalue,2) but not giving the require result. and i didn\'t find any other method in M

12条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-30 04:50

    double original = 12.123456789;  
    
    double truncated = Truncate(original, 2);  
    
    Console.WriteLine(truncated.ToString());
    // or 
    // Console.WriteLine(truncated.ToString("0.00"));
    // or 
    // Console.WriteLine(Truncate(original, 2).ToString("0.00"));
    
    
    public static double Truncate(double value, int precision)
    {
        return Math.Truncate(value * Math.Pow(10, precision)) / Math.Pow(10, precision);
    }
    

提交回复
热议问题