Truncate number of digit of double value in C#

后端 未结 12 685
死守一世寂寞
死守一世寂寞 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:49

    I'm sure there's something more .netty out there but why not just:-

    double truncVal = Math.Truncate(val * 100) / 100;
    double remainder = val-truncVal;
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-12-30 04:54

    If you are looking to have two points after the decimal without rounding the number, the following should work

    string doubleString = doublevalue.ToString("0.0000"); //To ensure we have a sufficiently lengthed string to avoid index issues
    Console.Writeline(doubleString
                 .Substring(0, (doubleString.IndexOf(".") +1) +2)); 
    

    The second parameter of substring is the count, and IndexOf returns to zero-based index, so we have to add one to that before we add the 2 decimal values.

    This answer is assuming that the value should NOT be rounded

    0 讨论(0)
  • 2020-12-30 05:01

    What have you tried? It works as expected for me:

    double original = 12.123456789;
    
    double truncated = Math.Truncate(original * 100) / 100;
    
    Console.WriteLine(truncated);    // displays 12.12
    
    0 讨论(0)
  • 2020-12-30 05:01

    How about:

    double num = 12.12890;
    double truncatedNum = ((int)(num * 100))/100.00;
    
    0 讨论(0)
  • 2020-12-30 05:01

    For vb.net use this extension:

    Imports System.Runtime.CompilerServices
    
    Module DoubleExtensions
    
        <Extension()>
        Public Function Truncate(dValue As Double, digits As Integer)
    
            Dim factor As Integer
            factor = Math.Pow(10, digits)
    
            Return Math.Truncate(dValue * factor) / factor
    
        End Function
    End Module
    
    0 讨论(0)
提交回复
热议问题