How do I parse a string number into a float with four decimal places?

P

Phil Mc

OK this should be bread and butter, easy to do, but I seem to be going
around in circles and not getting any answer to achieving this simple
task.

I have numbers in string format (they are coming in from an excel
sheet):
Examples.
45,666.0041
5664456.12
-5465.25568 ETC

I need to format this into a specified number of decimal places without
affecting anything else.

When I require 2 decimal places, this seams to work:

this.plotPoint =
float.Parse(String.Format("{0:F2}",row[fundReturnColumn]));

BUT when I want 4 decmail places:

this.plotPoint =
float.Parse(String.Format("{0:F4}",row[fundReturnColumn]));

I still get 2??????


I am sure that there is a simple explanation, but its driving me mad.}
 
R

Rick Lones

I think that your input strings specify too high a precision to fit a float.
With a single-precision float you could get at most 7 significant digits but,
for example, your first string has 9 significant digits. So I would suggest to
try parsing them into doubles instead.

HTH,
-rick-
 
P

Phil Mc

Hi thanks for the input.

Unfortunately I'm getting a error on ToString with only one argument

":No overload for method 'ToString' takes '1' arguments"

The way that I have got around this is to simply parse the string and
not convert to a number. I then use the string number in my sql
statement.


string numStr = String.Format(row[plotPointColumn].ToString().Trim());
numStr = String.Format("{0:0.0000}", numStr).Replace(",", "");

Not ideal, but getting the job done.

I would like to get to the bottom of the problem if anyone has any
ideas.
Thanks again for your help....
 
R

Rick Lones

I'm certainly not sure why unless it has to do with the data type of
"this.plotPoint", which you do not disclose. The following works for me on .Net
1.1 - is it not pretty close to what you are trying to do?

using System;

namespace ConsoleApplication1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
double d1, d2, d3;
string s1 = "45,666.0041";
string s2 = "5664456.12";
string s3 = "-5465.25568";
d1 = double.Parse(s1);
d2 = double.Parse(s2);
d3 = double.Parse(s3);
Console.WriteLine("{0}, {1}, {2}", new object[]{f1.ToString("#,0.0000"),

f2.ToString("#,0.0000"), f3.ToString("#,0.0000")});
Console.ReadLine();
}
}
}

Note that this does not work so well if you change "double" to "float" . . .

-rick-
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top