Search code examples
c#stringdoublecultureinfostring-conversion

double.ToString(0.55, {en-US}) returns .55 - C#


I have a method which returns a string.

In case 1 - return doubleVariable.ToString("0.55", {en-US}) returns 0.55 // **I need 0.55**

In case 2 - return doubleVariable.ToString("0.00", {en-US}) returns an empty string // **I need 0.00**

Any hints how to get rid of this?

EDIT:

METHOD

private string GetContent(
            NumericUserVariable templateNumericUserVariable,
            double doubleValue,
            CultureInfo cultureInfo)
        {

            string placeholder = "#";
            if (!templateNumericUserVariable.IsDecimal)
            {
                return doubleValue.ToString();
            }

            string decimalPlaces = placeholder;

            if (templateNumericUserVariable.DecimalPlace > 0)
            {
                decimalPlaces = decimalPlaces.PadRight(

                    // templateNumericUserVariable.DecimalPlace - 1,
                    templateNumericUserVariable.DecimalPlace, '#');

                return doubleValue.ToString(placeholder + "." + decimalPlaces, cultureInfo);
            }

            return doubleValue.ToString(placeholder, cultureInfo);
        }

Solution

  • To reach your objective you need to change the # character with a 0

    0 means, place a number in this position also if it is a zero value

    doubleVariable.ToString("0.00", cultureInfo);
    

    You can read about Custom Numeric Format here

    "0" - Zero placeholder Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

    Instead for the # character you could read

    "#" - Digit placeholder Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string.