Connecting Tech Pros Worldwide Help | Site Map

Format float

fmt
Guest
 
Posts: n/a
#1: Feb 5 '06
Hello,
I have float comming from database as .5. I need it to format to look
like .50. Please advice
Thanks

Jon Skeet [C# MVP]
Guest
 
Posts: n/a
#2: Feb 5 '06

re: Format float


fmt <simmaneni@fmtinv.com> wrote:[color=blue]
> I have float comming from database as .5. I need it to format to look
> like .50. Please advice[/color]

Use "f2" as the format specifier and format the string. For instance:

using System;

class Test
{
static void Main()
{
float f = 0.5f;
string x = f.ToString ("f2");
Console.WriteLine (x);
}
}

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
fmt
Guest
 
Posts: n/a
#3: Feb 5 '06

re: Format float


Thanks for fast reply. I sure will try..

fmt
Guest
 
Posts: n/a
#4: Feb 5 '06

re: Format float


Thanks Jon, I tried it but it gives 0.50. I don't want zero before
decimal. I want it to be .50.

Jon Skeet [C# MVP]
Guest
 
Posts: n/a
#5: Feb 5 '06

re: Format float


fmt <simmaneni@fmtinv.com> wrote:[color=blue]
> Thanks Jon, I tried it but it gives 0.50. I don't want zero before
> decimal. I want it to be .50.[/color]

And always to 2 decimal places? Try ".00" as the format string then.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
fmt
Guest
 
Posts: n/a
#6: Feb 5 '06

re: Format float


Thanks Jon,
I tried
string strReturn=(Rate.ToString()+".00");
string strReturn=(String.Format("{0:F2}%",Rate));
Both return.0.50...

fmt
Guest
 
Posts: n/a
#7: Feb 5 '06

re: Format float


Got it Jon,
I did
string strReturn=(Rate.ToString("#.00"));
It works.
Thanks

Jon Skeet [C# MVP]
Guest
 
Posts: n/a
#8: Feb 5 '06

re: Format float


fmt <simmaneni@fmtinv.com> wrote:[color=blue]
> I tried
> string strReturn=(Rate.ToString()+".00");
> string strReturn=(String.Format("{0:F2}%",Rate));
> Both return.0.50...[/color]

The first shouldn't - and doesn't on either 1.1 or 2.0 on my box:

using System;

class Test
{
static void Main()
{
string x = 0.5.ToString(".00");
Console.WriteLine (x);
}
}

prints out ".50" with both .NET versions.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Closed Thread