James Teare
James Teare

Reputation: 372

Converting string to float and formatting it (C#)

I am attempting to convert a float into a string.

I have a string (dividedstring[2]) that represents CPU load e.g. 0.00 or 0.01 or 0.54 etc.

I then would like to convert this into a float, so I do the following:

float.TryParse(dividedstring[2], out insertCPUvalue);

Now when I attempt to display the float e.g.:

MessageBox.Show(insertCPUvalue.ToString());

I get: "0", now I am assuming this is because the string "dividedstring[2]" was == "0.00", so it has just taken the decimal points of? - and rounded it to 0?

Upvotes: 2

Views: 1395

Answers (6)

BigL
BigL

Reputation: 1631

You should use invariant culture to parse your string like this.

float.TryParse("0.58", NumberStyles.Any, CultureInfo.InvariantCulture, out f);

Upvotes: 1

John Woo
John Woo

Reputation: 263703

float f = 0.0000666f;
Messagebox.Show(String.Format("{0:0,0.0000000}", f)); 

Upvotes: 1

Tamer Shlash
Tamer Shlash

Reputation: 9523

I think the problem is that you have 2 elements in dividedstring (array of 2 elements), and you are passing dividedstring[2] which is nothing (since the index starts from 0, so you have element 0 and element 1), this will throw an exception but TryParse will catch it and return assign 0, so try passing dividedstring[1] istead.

To make sure of that, just try using Parse:

insertCPUvalue.Parse(dividedstring[2]);

If my prediction is correct, this should throw an exception.

Upvotes: 0

fardjad
fardjad

Reputation: 20394

Use

MessageBox.Show(insertCPUvalue.ToString("F02"));

Upvotes: 0

Tudor
Tudor

Reputation: 62439

Try this:

MessageBox.Show(insertCPUvalue.ToString("0.00"));

Upvotes: 1

Daniel Mošmondor
Daniel Mošmondor

Reputation: 19956

If insertCPUvalue is float, you can use

MessageBox.Show(string.Format("{0:0.00}%", insertCPUvalue));

More on formats:

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

Upvotes: 5

Related Questions