简体   繁体   中英

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);
        }

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.

OK, so you are really complaining that (0.0).ToString("#.##") returns "" , right?

Try (0.0).ToString("0.00") instead.

Here (0.0) is the value of your doubleVariable .

But also consider:

doubleValue.ToString("F" + templateNumericUserVariable.DecimalPlace, cultureInfo)

for example (0.0).ToString("F2") gives "0.00" with two (fixed) decimals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM