Reputation: 372
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
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
Reputation: 263703
float f = 0.0000666f;
Messagebox.Show(String.Format("{0:0,0.0000000}", f));
Upvotes: 1
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
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