473,473 Members | 2,262 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Converting string to double

Hi, how can I parse string "? 20.000" to double ?
Nov 28 '06 #1
5 23440
Hi, how can I parse string "? 20.000" to double ?

Convert.ToDouble().

Best Regards,
Dustin Campbell
Developer Express Inc.
Nov 28 '06 #2
SMichal wrote:
Hi, how can I parse string "? 20.000" to double ?

Well, you obviously need to remove the '?' character and space before
it can be parsed to any numerical format. So I would use the Split()
function to remove the '?' character and the Trim() function to remove
the space:

string strNumber = "? 20.000";
strNumber = strNumber.Split('?');
strNumber.Trim();

Then use the Convert.ToDouble() function to convert the string to a
double value:

double myVal = Convert.ToDouble(strNumber);

If the value you are converting should be represented as currency or
requires a certain degree of precision you should use the
String.Format() function after converting your value. I hope that helps.

Nov 28 '06 #3
This would rely on the garbage text that proceeds the number always
being in the same format.

I think it would be better to convert the string to a character array
and examine each character for numeric validity before adding it to the
formatted string and parsing this as a double.

I've had a go but as people familliar to this forum may know, i'm a
complete beginner. My code doesn't work as it stands, perhaps someone
could offer a modification?

private void button1_Click(object sender, EventArgs e)
{
string somestring = "? 20.00";
char[] stringarray = somestring.ToCharArray();
string formattedstring = "0";
foreach (char c in stringarray)
{
if (((int)c >= 0 && (int)c <= 9) || c == '.')
{
formattedstring += c;
}
else
{
break;
}
}
double myDouble = double.Parse(formattedstring);
MessageBox.Show(myDouble.ToString());
}

Gary.;

Nov 28 '06 #4

Hey SMichal,

I cannot speak more glowingly about regular expressions ... try this
out:

//
// Setup our regex
//
Regex r = new Regex(@"(\d+.\d+)");
//
// Get the input
//
string input = "? 20.0000";
//
// Capture the value
//
string capturedValue = r.Match(input).Value;
//
// convert
//
double result = Double.Parse(capturedValue);

It will extract the doubles from any given string

On Tue, 28 Nov 2006 15:57:25 +0100, "SMichal"
<mi************@trygon-softwareberatung.dewrote:
>Hi, how can I parse string "? 20.000" to double ?
--

Bits.Bytes.
http://bytes.thinkersroom.com
Nov 28 '06 #5
On 28 Nov 2006 07:51:06 -0800, ga********@myway.com wrote:
>This would rely on the garbage text that proceeds the number always
being in the same format.

I think it would be better to convert the string to a character array
and examine each character for numeric validity before adding it to the
formatted string and parsing this as a double.

I've had a go but as people familliar to this forum may know, i'm a
complete beginner. My code doesn't work as it stands, perhaps someone
could offer a modification?

private void button1_Click(object sender, EventArgs e)
{
string somestring = "? 20.00";
char[] stringarray = somestring.ToCharArray();
string formattedstring = "0";
foreach (char c in stringarray)
{
if (((int)c >= 0 && (int)c <= 9) || c == '.')
{
formattedstring += c;
}
else
{
break;
}
}
double myDouble = double.Parse(formattedstring);
MessageBox.Show(myDouble.ToString());
}

Gary.;
First problem: When you enter your foreach loop, the first character
is '?', which activates the break; thus terminating the loop having
only processed one character. Remove the else part entirely as you
want to process all the characters in stringarray.

When you try this, you will find that it still does not work as you
expected.

Second problem: Your if statement starts:

if (((int)c >= 0 && (int)c <= 9) || c == '.')

When c = '2', (int)c is not 2, but the UTF encoding for 2. Change the
if to read:

if ((c >= '0' && c <= '9') || c == '.')

You did this correctly with the decimal point.

Your code now works after a fashion, though "20.02" would be a better
test number than 20.00. Try it to see why.

You ought to try running your code in the debugger. I just put one
breakpoint at the strat of the foreach loop, which found both your
problems easily.

Other points you may need to consider.

1 C# strings are immutable, you cannot change them. All you can do is
replace the old copy of the string with the new version. Better in
general to use a stringbuilder rather than a string in cases such as
this, where you do not know how long the final string is going to be.

2 Some countries use other characters such as ',' instead of '.' as a
decimal separator. Have a look at
System.Globalization.NumberFormatInfo.NumberDecima lSeparator.

3 You have no protection against a string like:
"? 20.02 ? 20.02 ? 20.03"
Try it and see what happens.

As a learning exercise you might also want to try writing a finite
state machine to parse real numbers out of a text string. It makes an
interesting little exercise.

rossum

Nov 28 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: rainmaker1234 | last post by:
Its very simple in VC++. In the followeing code I have declared a String, and a double than I am taking the string and converting it into Double. getch() at the end is only to pause the screen so...
1
by: Christine | last post by:
I was wondering if it is possible to convert an array that is of type string to type double so that matrix operations can be performed on it? I have a string array because I needed to split the...
4
by: diDE | last post by:
I want to convert a managed string array f.e. array<string^>^ Texts; // Elements 0: "ABC", 1: "HJO" to a TCHAR** or wchar_t** any ideas?
2
by: D. Shane Fowlkes | last post by:
Here's a good one. I've been using an Excel spreadsheet for the past couple of years to calculate a file's Estimated Download Time based off of a solid 50kbs connection (dial up). This is for a...
5
by: vivekaseeja | last post by:
Hi , Trying to convert a string value to a float value after reading the value from an XML file , but not sure what function to use. The following only works for integers Int32.Parse...
5
by: Asad | last post by:
Hi, I have retrieved values in a file. Used Double dval; String line; try{ BufferedReader in=new BufferedReader(new FileReader("File1.txt")); line = in.readLine();
5
oll3i
by: oll3i | last post by:
public class Cennik { private static Cennik instance = null; Map<String,Double> cennik = new HashMap<String,Double> (); private Cennik() { // prywatny konstruktor } public...
7
by: J | last post by:
Hi I'm just trying to convert a small program that was written in VB6 to VB.Net. I'm stumbling at the first hurdle! In VB I could do the following (ensuring that the textbox only contained...
2
by: clintonb | last post by:
Victor said: The double value that I'm trying to convert to GCSMoney (which is implemented as cents) was produced by multiplying a dollar amount by an interest rate to get interest. double...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.