Search code examples
c#stringmathintdouble

How do I covert the decimal places of a double to a string?


I have 4 examples:

double a = 1.05;
double b = 0.000056;
double c = 0.7812;
double d = 1.2;

What I want to do is first find how many place values there are. in this case

int inta = 2;
int intb = 6;
int intc = 4;
int intd = 1;

Then I want to create a string with "0" representing those digits. this is for a ToString()

string stra = ".00";
string strb = ".000000";
string strc = ".0000";
string strd = ".0";

So the only thing I have is a double. I need the place value, then how to create the string.


Solution

  • You could convert the double to a string, then get the substring:

    double a = 1.05;
    
    // Convert to string
    string aString = a.ToString();
    
    // Get substring
    string result = aString.Substring(aString.LastIndexOf('.'));
    
    // Get number of decimals
    int numDecimals = result.Length - 1;
    
    // Create string based on decimal count
    string zeroString = ".";
    for (int i = 0; i < numDecimals; i++) {
       zeroString += "0";
    }
    
    Console.WriteLine(result);
    Console.WriteLine(numDecimals);
    Console.WriteLine(zeroString);
    // .05
    // 2
    // .00
    

    ** To ensure this works for all cultures and not only those who utilize '.' as the decimal separator, you could replace:

    LastIndexOf('.')

    with

    LastIndexOf(System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalSeparator)

    (Thanks @John)