Nomesh Gajare
Nomesh Gajare

Reputation: 855

Float to String Conversion

I want to convert float value to string.

Below is the code which i am using for the conversion.

static void Main(string[] args)
        {
            string s =string.Format("{0:G}", value);                
            Console.Write(s);
            Console.ReadLine();
        }

and it outputs as 2.5

But my problem is i want to get the value as 2.50 because i want to compare it with original value later in my project.

so please suggest me if there are any ways to do it?

Upvotes: 7

Views: 50816

Answers (3)

Sadique
Sadique

Reputation: 22823

You should be using {0:N2} to format to two decimal places.

string.Format("{0:N2}", 2.50)

For 3 decimal places:

string.Format("{0:N3}", 2.50)

And so on.

You can also store the value in a string this way without worrying about precision and then convert your value where you are testing for comparison as string:

string strDecimalVal = Convert.ToString( 2.5000001);

Upvotes: 11

Heinzi
Heinzi

Reputation: 172220

because i want to compare it with original value later in my project.

...then you will need to store the number of decimal places the original value had. Once the value is a float, this information is lost. The float representations of 2.5, 2.50 and 2.500 are exactly the same.

So, basically, you have the following possibilities (in order of preference):

  • Don't do a string comparison between the old and the new value. Convert both values to float and then compare them (with a margin of error since floats are not precise).
  • Store the number of decimal places of the old value and then use myFloat.ToString("F" + numDecimals.ToString()) to convert it to a string.
  • Store the value as a string instead of a float. Obviously, you won't be able to do math on that value.

Alternatively, if you do not insist on using floats, decimals might suit your purpose: The do store the number of significant digits:

decimal x = Decimal.Parse("2.50", CultureInfo.InvariantCulture);
decimal y = Decimal.Parse("2.500", CultureInfo.InvariantCulture);

Console.WriteLine(x.ToString()); // prints 2.50
Console.WriteLine(y.ToString()); // prints 2.500

Upvotes: 5

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

Try this

Console.WriteLine("{0:F2}", 2.50);
Console.WriteLine("{0:0.00}", 2.50);
Console.WriteLine("{0:N2}", 2.50);

Version 1 and 2 are almost similar, but 3 is different. 3 will include number separators when number is large.

For example the following outputs 454,542.50

Console.WriteLine("{0:N2}", 454542.50);

More on MSDN

Upvotes: 1

Related Questions