Formatting a Floating Point String

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • ngn

    #1

    Formatting a Floating Point String

    How do you format the number of decimal places in a
    floating point number converted to a string?

    I simply use the ToString() method on the float variable,
    but I cannot find how to format it a #.## format (only 2
    places of decimal).

    float n = 0.12348528f
    string str = n.ToString();
    // ??? How do I now format str ???
  • Jon Skeet

    #2
    Re: Formatting a Floating Point String

    ngn <niallgnaughton @yahoo.co.uk> wrote:[color=blue]
    > How do you format the number of decimal places in a
    > floating point number converted to a string?
    >
    > I simply use the ToString() method on the float variable,
    > but I cannot find how to format it a #.## format (only 2
    > places of decimal).
    >
    > float n = 0.12348528f
    > string str = n.ToString();
    > // ??? How do I now format str ???[/color]

    string str = n.ToString("g2" );

    Have a look in MSDN for "standard numeric format strings" for more
    information.

    --
    Jon Skeet - <skeet@pobox.co m>
    Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

    If replying to the group, please do not mail me too

    Comment

    • Christian

      #3
      Re: Formatting a Floating Point String

      double n = 5.2364;
      string str = n.ToString("#,0 0");


      Comment

      Working...