How to insert a thousand separator (comma) with convert to double

前端 未结 7 2252
误落风尘
误落风尘 2020-12-05 03:43

I am trying to format the contents of a text box:

this.lblSearchResults1.Text =
    Convert.ToDouble(lblSearchResults1.Text).ToString(); 

H

相关标签:
7条回答
  • 2020-12-05 04:20

    An alternative to the above mentioned responses would be to use

    this.lblSearchResults1.Text = String.Format("{0:N}", Convert.ToDouble(lblSearchResults1.Text))
    

    If you wanted decimal places, just enter the amount of decimal places you wish to have after the N. The following example will return the value with 2 decimal places.

    this.lblSearchResults1.Text = String.Format("{0:N2}", Convert.ToDouble(lblSearchResults1.Text))
    

    See http://msdn.microsoft.com/en-us/library/system.string.format.aspx for more information.

    0 讨论(0)
  • 2020-12-05 04:27

    For complete custom control, use ... .ToString("#,##0.00") or variations thereof. The . and , will be replaced by culture dependent symbols. In most of europe you'd get 1.234,56.
    Another useful picture is 0.0#.

    To use a pattern depending on the users (or on a selected) culture, use The Numeric ("N") Format Specifier, as in .ToString("N") or "... {0:N}".

    0 讨论(0)
  • 2020-12-05 04:36

    If you take a closer look at Standard Numeric Format Strings you can try one of the following:

    .ToString("n", CultureInfo.GetCultureInfo("en-US"))
    .ToString("n", CultureInfo.GetCultureInfo("de-DE"))
    .ToString("n", CultureInfo.CurrentCulture)
    
    0 讨论(0)
  • 2020-12-05 04:37

    Do not cast integral to double to do this!
    Use NumberFormatInfo helper class, e.g:

        var nfi = new NumberFormatInfo() {
            NumberDecimalDigits = 0,
            NumberGroupSeparator = "."
        };
    
        var i = 1234567890;
        var s = i.ToString("N", nfi); // "1.234.567.890"
    
    0 讨论(0)
  • 2020-12-05 04:38

    Looking at the standard numeric format strings:

    You can most easily use 'N' which will do the right thing based on the user culture, so in your case you can just add "N" as a param to the ToString

    ([double]12345.67).ToString("N")
    

    12,345.67

    0 讨论(0)
  • 2020-12-05 04:39

    The easiest way to do it would be something like:

    Convert.ToDouble("1234567.12345").ToString("N")
    

    If you want to control the decimal places you can do something like:

    Convert.ToDouble("1234567.12345").ToString("N3")
    

    In general look at the overloads on ToString for more exciting possibilities.

    0 讨论(0)
提交回复
热议问题